Attaching Files to an E-Mail Message - Java Network

Java examples for Network:EMail

Description

Attaching Files to an E-Mail Message

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Main {

  public static void main(String[] args) {
    String host = "smtp.somewhere.com";
    String from = "someone@somewhere.com";
    String to = "anotherone@somewhere.com";

    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);

    Session session = Session.getDefaultInstance(properties, null);

    MimeMessage message = new MimeMessage(session);
    try {
      message.setFrom(new InternetAddress(from));
      message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Subject Test");

      // Create Mime Content
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent("This is a test message", "text/plain");

      MimeBodyPart fileBodyPart = new MimeBodyPart();
      fileBodyPart.attachFile("<path-to-attachment>/attach.txt");

      MimeBodyPart fileBodyPart2 = new MimeBodyPart();
      fileBodyPart2.attachFile("<path-to-attachment>/attach2.txt");

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      multipart.addBodyPart(fileBodyPart);
      // add another body part to supply another attachment
      multipart.addBodyPart(fileBodyPart2);

      message.setContent(multipart);
      Transport.send(message);
    } catch (MessagingException | IOException e) {
      e.printStackTrace();
    }
  }
}

Related Tutorials