Spring Mail inline images doesn't work in Mac Mail - spring

When I use Spring to send mail inline images, I found it doesn't show image in Mac Mail App, but it shows it in web Zimbra. My code is as follows, what's wrong with it?
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setDefaultEncoding("UTF-8");
mailSender.setHost(Consts.MAIL_HOST);
mailSender.setUsername(Consts.MAIL_USER);
mailSender.setPassword(Consts.MAIL_PASSWORD);
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setFrom(mailSender.getUsername());
InternetAddress[] addresses = InternetAddress.parse("sartisty#gmail.com");
helper.setTo(addresses);
helper.setSubject("test");
helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
FileSystemResource res = new FileSystemResource(new File("/Users/yanshuai/widget-ca3dc599-9c30-43de-9a2d-b62903301b59.png"));
helper.addInline("identifier1234", res);
mailSender.send(msg);

Related

How to change the from address in send grid email

I have configured the send grid API for email service in my spring boot APP. And, it's working fine. I wanted to change the from address as "no-reply#xyz.com" instead of "apikey". But, I couldn't.
Also, I tried it using JavaMaiSender. But, no luck.
Could you please anyone let me know?
public void sendEmailUsingSendgrid(EmailRequest emailRequest) throws IOException {
String text = getEmailTemplate(emailRequest);
SendGrid sg = new SendGrid(sendGridApi);
sg.addRequestHeader("X-Mock", "true");
Request request = new Request();
Mail mail = new Mail();
mail.setFrom(new Email(emailRequest.getFr()));
mail.setSubject(emailRequest.getSbjt());
mail.addContent(new Content("text/html", text));
List<String> mailList = Arrays.asList(emailRequest.getTo());
for (String to : mailList) {
Personalization p1 = new Personalization();
p1.addTo(new Email(to));
mail.addPersonalization(p1);
}
mail.setReplyTo(new Email("noreply#xyz.com"));
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
}
Properties
# SENDGRID
sendgrid-api-key=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

Microsoft outlook doesn't shows German umlauts

I have an email send through SMTP which contains some German characters (umlauts). The encoding used is 'UTF-8', but the content is not displaying correctly.
But when I choose the 'view source' in outlook app (by right click), the result shows all the umlauts. See in high lighted.
How to solve this problem? The content of the mail is created programmatically through the following code.
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
mimeMessage.setContent("<html><head><meta charset=\"UTF-8\"></head><body>Hallo Saju Paul,<p>Wir.....", "text/html");
helper.setTo("sender#sender.com");
helper.setSubject("Setze dein Passwort zurück");
helper.setFrom("undefined#variables.env");
mailSender.send(mimeMessage);
where mailSender is
org.springframework.mail.javamail.JavaMailSender
How to solve this problem?

JavaMail requires an InputStreamSource that creates a fresh stream for every call

I'm trying to send an attachment using JavaMail via Spring 2.5's MailSender, but I keep getting this error:
Passed-in Resource contains an open stream: invalid argument.
JavaMail requires an InputStreamSource that creates a fresh stream for every call.
I am using an InputStreamResource :
InputStream crofileInputStream = emailDraft.getAttachmentCroFile().getInputStream();
InputStream nacfileInputStream = emailDraft.getAttachmentNacFile().getInputStream();
InputStream sourcefileInputStream = emailDraft.getAttachmentSourceFile().getInputStream();
InputStreamSource[] attachments = {new InputStreamResource(crofileInputStream),new InputStreamResource(nacfileInputStream),new InputStreamResource(sourcefileInputStream)};
sentEmailLog = mailSenderService.sendMIMEMessage(emailDraft, attachmentFileNames, attachments);
this last instruction calls
MimeMessageHelper.addAttachment(fileName,attachments[i]) for each attachment.
Please how could i solve this issue ?
Thanks for you help.
Try to use javax.mail.util.ByteArrayDataSource
String mailTo = message.getHeaders().get("emailAddress", String.class);
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
ByteArrayDataSource attachment = new ByteArrayDataSource(message.getPayload(), "application/octet-stream");
helper.addAttachment("document.zip", attachment);
helper.setText("text content of the email");
You could also check this example:
https://www.javatips.net/api/javax.mail.util.bytearraydatasource

How can attachment names be retrieved from a JavaMailSender exception?

I'm using org.springframework.mail.javamail.JavaMailSender (Spring Framework 4.1.6). I'm sending multiple emails by calling:
mailSender.send(mimeMessagePreparators);
where mimeMessagePreparators is a MimeMessagePreparator array. Each MimeMessagePreparator is built as follows:
MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
// get the subscribers of the attachment and put them as the recipients
// of this email
mimeMessageHelper.setTo(subscribers);
// all email have the same from, bcc, reply to, subject, and body
String fromEmailAddress = emailTemplate.getFromEmailAddress();
mimeMessageHelper.setFrom(fromEmailAddress);
// note: bcc the sender so that they get the email too
mimeMessageHelper.setBcc(fromEmailAddress);
// this will help on auto replies and bounce messages
// also it should help on deliverability
mimeMessageHelper.setReplyTo(fromEmailAddress);
String subject = emailTemplate.getSubject();
mimeMessageHelper.setSubject(subject);
String emailBody = emailTemplate.getBody();
mimeMessageHelper.setText(OPEN_EMAIL_TAGS + emailBody + CLOSE_EMAIL_TAGS, true);
// get the physical file and add as an email attachment
FileSystemResource file = new FileSystemResource(new File(directory, attachment.getName()));
mimeMessageHelper.addAttachment(attachment.getName(), file);
}
};
I need to know which emails failed (i.e. had a MailException) and eventually tell the user the names of the attachments associated with emails that failed. How can I retrieve the attachment names from the exception? So far, I have
try {
mailSender.send(mimeMessagePreparators);
} catch (MailSendException mailSendException) {
Map<Object, Exception> map = mailSendException.getFailedMessages();
for (Map.Entry<Object, Exception> entry : map.entrySet()) {
MimeMessage mimeMessage = (MimeMessage) entry.getKey();
// get attachment names from mimeMessage? or preferably
// get in a more simplistic way using a helper such as MimeMessageHelper
} catch (MailException mailException) {
// how do I get attachment names here?
}
If you have a bunch of MimeMessage objects, see the JavaMail FAQ entries starting here:
How do I tell if a message has attachments?
Essentially, you need to iterate over the parts in the message, determine which ones represent attachments, and then access whatever metadata or headers in the part you think represent the attachment "name".

How to send email with attachments

I want to send an email with an image attached with it. I am using spring 3 with velocity templates. I am able to do that but for some reasons when I add an extension with the image name I don't get the email delivered.
Following is the code I am using for it:
private MimeMessage createEmail(Application application, String templatePath, String subject, String toEmail, String fromEmail, String fromName) {
MimeMessage mimeMsg = mailSender.createMimeMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("application", application);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);
text = text.replaceAll("\n", "<br>");
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setSubject(subject);
helper.setTo(toEmail);
if (fromName == null) {
helper.setFrom(fromEmail);
} else {
try {
helper.setFrom(fromEmail, fromName);
} catch (UnsupportedEncodingException e) {
helper.setFrom(fromEmail);
}
}
helper.setSentDate(application.getDateCreated());
helper.setText(text, true);
InputStream inputStream = servletContext.getResourceAsStream("images/formstack1.jpg");
helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));
} catch (MessagingException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return mimeMsg;
}
Using the code above I could add formstack1 as attachment but it has no extension so I don't get the formstack1.jpg image file. But when I use formstack1.jpg for the name of resource to be attached in helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); as formstack1 changed to formstack1.jpg I don't get even the email delivered. I am using smtp.gmail.com and 25 for port. I do get the email sent successfully message on the console though. But the email
is never delivered.
EDIT: If I keep it like helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); and change the extension from nothing to .jpg while downloading the attached image I do get the desired image.
Could someone help me understand why is it happening and how send email with 1 or more attachments using spring 3.
Thanks.
You should better use Apache Commons HtmlEMail
http://commons.apache.org/email/userguide.html

Resources