Java Email MimeMultipart send email with attachment

Description

Java Email MimeMultipart send email with attachment


import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
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 to = "usr.some@gmail.com";
      final String user = "usr.some@gmail.com";
      final String password = "some.usr";
      String mailHost = "smtp.gmail.com";

      Properties props = new Properties();
      props.setProperty("mail.smtp.host", mailHost);
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");

      Session session = Session.getInstance(props, new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
         }/*from   w ww.j a va  2  s . com*/
      });
      // session.setDebug(true);
      try {
         MimeMessage msg = new MimeMessage(session);
         msg.addRecipients(Message.RecipientType.TO, to);
         msg.setSubject("Mail with attachment");

         Multipart multipart = new MimeMultipart();

         MimeBodyPart part1 = new MimeBodyPart();
         MimeBodyPart part2 = new MimeBodyPart();

         // part1.setContent("This mail has an attachment.", "text/plain");
         part1.setText("This mail has an attachment.");

         String filename = "Main.java";
         DataSource source = new FileDataSource(filename);
         DataHandler dh = new DataHandler(source);

         part2.setDataHandler(dh);
         part2.setFileName(filename);

         part2.attachFile(filename);

         multipart.addBodyPart(part1);
         multipart.addBodyPart(part2);

         msg.setContent(multipart);

         Transport.send(msg);

         System.out.println("msg sent....");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related