Tuesday, 10 September 2013

JavaMail API – Sending email via Gmail SMTP

You must have SMTP server that is responsible to send mails.
You can use one of the following techniques to get SMTP server:

Install and use any SMTP server such as Apache James server,
Postcast server etc  (or)

Use the SMTP server provided by other companies e.g. gmail etc

Here is an example to send a simple e-mail from your machine.
Here it is assumed that your localhost is connected to the internet
and capable enough to send an email. 

EmailVO.java:
package email;
import java.util.Map;
import java.util.List;
public class EmailVO { private String to; private String from; private String subject; private String templateName; private Integer templateCode; private Map<String,String> variableValues; private String content; private Boolean isContentHtml; private String cc; private String bcc; private String replyTo; private String text; private List<Map<String, Object>> couponsList; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public Integer getTemplateCode() { return templateCode; } public void setTemplateCode(Integer templateCode) { this.templateCode = templateCode; } public Map<String, String> getVariableValues() { return variableValues; } public void setVariableValues(Map<String, String> variableValues) { this.variableValues = variableValues; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Boolean getContentHtml() { return isContentHtml; } public void setContentHtml(Boolean contentHtml) { isContentHtml = contentHtml; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getBcc() { return bcc; } public void setBcc(String bcc) { this.bcc = bcc; } public String getReplyTo() { return replyTo; } public void setReplyTo(String replyTo) { this.replyTo = replyTo; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<Map<String, Object>> getCouponsList() { return couponsList; } public void setCouponsList(List<Map<String, Object>> couponsList) { this.couponsList = couponsList; } }  
Constants.java: 
package email; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class Constants { 
 
 public static final String host = "smtp.gmail.com";
 public static final String username="alekhya@gmail.com";
 public static final String password="alekhya";
 public static final String from="alekhya@gmail.com";
  
}
EmailUtil.java:
package email; import javax.mail.internet.MimeMessage; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSenderImpl; public class EmailUtil implements Runnable{ private JavaMailSenderImpl javaMailSender; private MimeMessage mimeMessage; public EmailUtil(JavaMailSenderImpl javaMailSender, MimeMessage mimeMessage) { this.javaMailSender = javaMailSender; this.mimeMessage = mimeMessage; } public void run() { try { this.javaMailSender.send(this.mimeMessage); System.out.println("Sent main successfully"); } catch (MailException ex) { ex.printStackTrace(); } } }
EmailService.java: 
package email;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.sun.corba.se.impl.orbutil.closure.Constant;
import com.tb.module.service.Constants;

@Service
public class EmailService {

   
    private static MailSender mailSender;
    private static VelocityEngine velocityEngine;
    
    static{
     if(mailSender == null){
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      JavaMailSenderImpl javamailSender = new JavaMailSenderImpl();
      javamailSender.setHost(Constants.host);
      javamailSender.setPort(587);
      javamailSender.setUsername(Constants.username);
      javamailSender.setPassword(Constants.password);
      javamailSender.setJavaMailProperties(props);
      mailSender = javamailSender;
     }
    }
    
    public void sendEmail(EmailVO emailVO){
      
     MimeMessage msg = ((JavaMailSenderImpl)mailSender).createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(msg,true);
            helper.setTo(emailVO.getTo());
            helper.setSubject(emailVO.getSubject());
            helper.setFrom(emailVO.getFrom());
          
            helper.setText(emailVO.getContent());
        }catch(MessagingException ex){
         ex.printStackTrace();
        }
        try
        {
            Thread mailThread =
            new Thread(new EmailUtil((JavaMailSenderImpl)mailSender, msg));
            mailThread.start();
         
        }
        catch (MailException ex)
        {
           ex.printStackTrace();
        }

    }
    public MailSender getMailSender() {
        return mailSender;
    }
    public static void main(String[] args) {
     EmailService emailService=new EmailService();
     EmailVO emailVO=new EmailVO();

        emailVO.setTo("alekhya@gmail.com");

        emailVO.setFrom(Constants.from);

        emailVO.setSubject("hi");

        emailVO.setTemplateName("hi");

        Map<String , String> map=new HashMap<String , String>();
        map.put("msg","GoodMorning");
        map.put("body1","GoodMorning");

        StringBuffer content = new StringBuffer();
        content.append("Hi, \n\n\n");
        content.append(" Test mail ?\n\n");
        content.append("Regards, \n"+ "alekhya");
        emailVO.setContent(content.toString());
        emailVO.setVariableValues(map);

        emailService.sendEmail(emailVO);
   
 }
}
 
 

1 comment:

Anonymous said...

Very informative; Thanks for sharing. I would like to share about a new android email API from Aspose by the name of Aspose.Email for Android . enables developers to design Android applications for managing & manipulating Outlook email file formats without using MS Outlook. I am sure the community going to love it as I do. Thanks once again