Email with Attachments
Sometimes a simple text email is not enough. You need to send invoices, reports, images, or documents. Email with attachments requires a more sophisticated approach using
MimeMessage and MimeMessageHelper.Spring's
MimeMessageHelper makes it easy to create complex emails with attachments, HTML content, and inline images.Sending email with attachment:
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmailWithAttachment(
String to,
String subject,
String body,
String attachmentPath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true); // true = multipart
helper.setTo(to);
helper.setSubject(subject);
helper.setText(body);
helper.setFrom("your-email@gmail.com");
// Add attachment
FileSystemResource file = new FileSystemResource(new File(attachmentPath));
helper.addAttachment(file.getFilename(), file);
mailSender.send(message);
}
}
Sending HTML email with inline image:
public void sendHtmlEmailWithInlineImage() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo("recipient@example.com");
helper.setSubject("HTML Email with Image");
String htmlContent = "Welcome!
Here is our logo:
";
helper.setText(htmlContent, true); // true = isHtml
// Add inline image
FileSystemResource image = new FileSystemResource("path/to/logo.png");
helper.addInline("logoImage", image);
mailSender.send(message);
}
Sending email to multiple recipients:
helper.setTo("user1@example.com", "user2@example.com"); // TO
helper.setCc("cc@example.com"); // Carbon Copy
helper.setBcc("bcc@example.com"); // Blind Carbon Copy
Using templates for email body:
For complex emails, use Thymeleaf or FreeMarker to generate HTML content dynamically.
@Autowired
private SpringTemplateEngine templateEngine;
public void sendTemplateEmail(String to, String templateName, Context context) throws MessagingException {
String htmlContent = templateEngine.process(templateName, context);
// ... set htmlContent to helper.setText(htmlContent, true)
}
Two Minute Drill
- Use MimeMessage and MimeMessageHelper for complex emails.
- MimeMessageHelper constructor with true enables multipart (attachments).
- addAttachment() adds file attachments.
- addInline() adds inline images referenced with cid: in HTML.
- setText(html, true) sends HTML emails.
- Support TO, CC, BCC for multiple recipients.
Need more clarification?
Drop us an email at career@quipoinfotech.com
