Я использую электронную почту sendgrid с Java. Я пытаюсь отправить несколько вложений, но почему-то в письме отсутствует 1 или 2 файла. Иногда все вложения отправляются. Я тоже проверил код статуса. Его 202 каждый раз. Это непредсказуемое поведение. Кто-нибудь может указать, если я что-то упускаю.
import com.sendgrid.*;
import com.sendgrid.Attachments.Builder;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.List;
public class SendGridUtils {
private InputStream fileContent;
private List<File> files;
public boolean sendEmail() {
try {
String sendTo="sento@gmail.com";
String subject="some_subject";
String body="some_body";
String sendGridAPIKey = "some_key";
String fromEmail = "from@gmail.com";
String emailTitle = "some_title";
files.add(new File("abc.png"));
files.add(new File("xyz.png"));
files.add(new File("pqr.png"));
files.add(new File("rty.png"));
files.add(new File("ghj.png"));
Email from = new Email(fromEmail, emailTitle);
Email to = new Email(sendTo);
Content content = new Content("text/html", body);
Mail mail = new Mail(from, subject, to, content);
Personalization personalization = new Personalization();
personalization.addTo(to);
mail.addPersonalization(personalization);
attachFiles(mail);
SendGrid sg = new SendGrid(sendGridAPIKey);
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
return true;
} catch (Exception ex) {
ex.printStackTrace();
return true;
} finally {
if (fileContent != null) {
try {
fileContent.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (files != null) {
for (File f : files) {
if (f.exists()) {
f.delete();
}
}
}
}
}
private void attachFiles(Mail mail) throws IOException {
if (files != null) {
for (File f : files) {
String fName = f.getName();
if (!StringUtils.isBlank(fName)) {
this.fileContent = new FileInputStream(f);
Attachments attachments = new Builder(fName, fileContent).withDisposition("attachment")
.withType("image/png").build();
mail.addAttachments(attachments);
}
}
}
}
}
Зависимость Maven
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>4.3.0</version>
</dependency>