Source Code : How do I send an email with attachment

How do I send an email with attachment

package org.kodejava.example.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

public class SendEmailWithAttachment {
  public static void main(String[] args) {
  SendEmailWithAttachment demo = new SendEmailWithAttachment();
  demo.sendEmail();
  }

  public void sendEmail() {
  //
  // Defines the E-Mail information.
  //
  String from = "kodejava@gmail.com";
  String to = "kodejava@gmail.com";
  String subject = "Important Message";
  String bodyText = "This is a important message with attachment.";

  //
  // The attachment file name.
  //
  String attachmentName = "D:/Data/LoremIpsum.docx";

  //
  // Creates a Session with the following properties.
  //
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.transport.protocol", "smtp");
  props.put("mail.smtp.starttls.enable","true");
  Session session = Session.getDefaultInstance(props);

  try {
  InternetAddress fromAddress = new InternetAddress(from);
  InternetAddress toAddress = new InternetAddress(to);

  //
  // Create an Internet mail message.
  //
  MimeMessage message = new MimeMessage(session);
  message.setFrom(fromAddress);
  message.setRecipient(Message.RecipientType.TO, toAddress);
  message.setSubject(subject);
  message.setSentDate(new Date());

  //
  // Set the email message text.
  //
  MimeBodyPart messagePart = new MimeBodyPart();
  messagePart.setText(bodyText);

  //
  // Set the email attachment file
  //
  FileDataSource fileDataSource = new FileDataSource(attachmentName);

  MimeBodyPart attachmentPart = new MimeBodyPart();
  attachmentPart.setDataHandler(new DataHandler(fileDataSource));
  attachmentPart.setFileName(fileDataSource.getName());

  //
  // Create Multipart E-Mail.
  //
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messagePart);
  multipart.addBodyPart(attachmentPart);

  message.setContent(multipart);

  //
  // Send the message. Don't forget to set the username and password to authenticate to the
  // mail server.
  //
  Transport.send(message, "kodejava", "password");
  } catch (MessagingException e) {
  e.printStackTrace();
  }
  }
}