Java Email send email with attachment

Description

Java Email send email with attachment


import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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) {
      try {/*w  w  w .j a v  a2s  . c  o m*/
         Properties props = System.getProperties();
         props.put("mail.smtp.starttls.enable", "true");
         props.put("mail.smtp.host", "smtp.gmail.com");
         props.put("mail.smtp.auth", "true");
         props.put("mail.smtp.port", "465"); // smtp port
         Authenticator auth = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication("username-gmail", "password-gmail");
            }
         };
         Session session = Session.getDefaultInstance(props, auth);
         MimeMessage msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress("username-gmail@gmail.com"));
         msg.setSubject("Try attachment gmail");
         msg.setRecipient(RecipientType.TO, new InternetAddress("username-gmail@gmail.com"));
         // add at least simple body
         MimeBodyPart body = new MimeBodyPart();
         body.setText("Try attachment");
         // do attachment
         MimeBodyPart attachMent = new MimeBodyPart();
         FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
         attachMent.setDataHandler(new DataHandler(dataSource));
         attachMent.setFileName("file-sent.txt");

         attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
         Multipart multipart = new MimeMultipart();
         multipart.addBodyPart(body);
         multipart.addBodyPart(attachMent);
         msg.setContent(multipart);
         Transport.send(msg);
      } catch (Exception ex) {
         ex.printStackTrace();;
      }
   }

}



PreviousNext

Related