How to send Mail in Java

package com.sendMail;

import java.io.FileInputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 *
 * @author ananddw
 *
 */

public class EmailService {

public boolean  SendMail(String voucherID){
  
    boolean flag=false;
    Properties props = System.getProperties();
    props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
    props.put("mail.smtp.port", "587"); //TLS Port
    props.put("mail.smtp.auth", "true"); //enable authentication
    props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS

    StringBuilder mailBody = new StringBuilder("Hi,<br/><br/>");
    mailBody.append("Mail is Created Succesfully<br/><br/>");
    mailBody.append(" Time: " + System.currentTimeMillis() + ""+ "<br/><br/>");
  
    mailBody.append("Send By : Anand <br/><br/><br/>");
    mailBody.append("Thanks & Regards<br/>Anand Dwivedi");

    Session session = Session.getInstance(props,null);
    MimeMessage message = new MimeMessage(session);

    System.out.println("Port: "+session.getProperty("mail.smtp.port"));

    // Create the email addresses involved
    try {
        String [] mailTo=new String[] {"test@gmail.com" };
        InternetAddress[] addressTo = new InternetAddress[mailTo.length];
        for (int i = 0; i < mailTo.length; i++) {
            addressTo[i] = new InternetAddress(mailTo[i]);
            addressTo[i].validate();
        }
        InternetAddress from = new InternetAddress("test@gmail.com");
        message.setSubject(" Message Mail");
        message.setFrom(from);
        message.addRecipients(Message.RecipientType.TO,addressTo);

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart("alternative");

        // Create your text message part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("some text to send");

        // Add the text part to the multipart
        multipart.addBodyPart(messageBodyPart);

        // Create the html part
        messageBodyPart = new MimeBodyPart();
        String htmlMessage = mailBody.toString();
        messageBodyPart.setContent(htmlMessage, "text/html");


        // Add html part to multi part
        multipart.addBodyPart(messageBodyPart);

        // Associate multi-part with message
        message.setContent(multipart);

        // Send message
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com", "test@gmail.com", "Gmail password");
        System.out.println("Transport: "+transport.toString());
        transport.sendMessage(message, message.getAllRecipients());

        flag=true;
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        flag=false;
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        flag=false;
    }
    return flag;
}

public static void main(String []args){    
EmailService service=new EmailService();
  service.SendMail();
}
}


PS: Make sure that attache all the required Jars as well as 

Turn On This service if it is off: https://www.google.com/settings/security/lesssecureapps

Comments

Popular posts from this blog

Converting JSONArray into CSV file in java

Java Design pattern

Map class field to map