Sending Gmail from Java

Further to my java stuff from yesterday, I wanted to add the ability to send myself an email when the task completes successfully.  I poked around the web and found this solution:

JavaMail API – Sending email via Gmail SMTP example

The first example worked for me, once I enabled the ‘less secure’ apps method for my Gmail account.

I modified the above code, using the snippet at this link.  This let me send an attachment with the email!

public class SendAttachmentInEmail {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "";

      // Sender's email ID needs to be mentioned
      String from = "";

      final String username = "username";//change accordingly
      final String password = "password";//change accordingly

      // Assuming you are sending email through
      String host = "";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("", "");
      props.put("mail.smtp.port", "587");

      // Get the Session object.
      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);

      try {
         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.

         // Set Subject: header field
         message.setSubject("Testing Subject");

         // Create the message part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Now set the actual message
         messageBodyPart.setText("This is message body");

         // Create a multipar message
         Multipart multipart = new MimeMultipart();

         // Set text message part

         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "/home/cwg/file.txt"; //full path to file you want to attach
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename); //attachment name in the email

         // Send the complete message parts

         // Send message

         System.out.println("Sent message successfully....");
      } catch (MessagingException e) {
         throw new RuntimeException(e);

Leave a Reply