CODEXE

Java Send Email

There is multiple methods to send email:

  1. Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or)
  2. Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or)
  3. Use the SMTP Server provided by other companies e.g. gmail etc.

The following code implements the third method which can be used to send both text and html email.

MailUtil - Set basic info of email


public class MailUtil {
	public static final int HTML_FORMAT = 1;
	public static final int TEXT_FORMAT = 2;
	public static final String PASSWORD = "set email password";
	public static final String root = "http://localhost:8080";
	/***************Sign up email******************/
	public static final String ACCOUNT_ACTIVATION_SENDER = "youremail@gmail.com";
	public static final String ACCOUNT_ACTIVATION_SUBJECT = "subject";
	public static String generateAccountActivationEmail(String hashCode, String rootURL) {
		String content = "<html><head></head><body>Thanks you for your registration. Please activate your account in 24 hours.<a href='"
				+ rootURL+"/signup/confirm?code=" + hashCode+"'>"+rootURL+"/signup/confirm?code=" + hashCode
                + "</a></body></html>";
		return content;
	}
}
           	

MailDispatcher - Send email


public class MailDispatcher implements Runnable {
	private String receiver;
	private String sender = "youremail@gmail.com";//default
	private String password = "youremailpassword";//default
	
	//email details
	private String subject;
	private String content;
	private int contentType;
	
	public MailDispatcher(String sender, String password, String receiver, String subject, String content,int contentType) {
		this.sender = sender;
		this.password = password;
		this.receiver = receiver;
		this.subject = subject;
		this.content = content;
		this.contentType = contentType;
	}
	/**
	 * If you want to use fixed sender and password, just set the default value of sender and password in this class. 
	 * For exmaple, private String sender = "codexe.net@gmail.com"; private String password = "********";
	 * Then call this method to set other info.
	 * @param receiver
	 * @param subject
	 * @param content
	 * @param contentType
	 */
	public MailDispatcher(String receiver, String subject, String content,int contentType) {
		this.receiver = receiver;
		this.subject = subject;
		this.content = content;
		this.contentType = contentType;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
	//	String from = "codexe.net@gmail.com";
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");
		//get session
		Session session = Session.getDefaultInstance(props, new Authenticator(){
			protected PasswordAuthentication getPasswordAuthentication() {    
				return new PasswordAuthentication(sender,password);  
			}   
		});
		//compose message
		try {
			MimeMessage message = new MimeMessage(session);
			//Set sender's name
			message.setFrom(new InternetAddress(MailUtil.TEST_USER,"SGBING"));
			//Set reveiver
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.receiver));
			//Set subject
			message.setSubject(subject);
			
			//Set email content. The format can be  html or text only.
			if(contentType == MailUtil.HTML_FORMAT) {
				message.setContent(content, "text/html;charset=UTF-8");
			}
			else if(contentType == MailUtil.TEXT_FORMAT){
				message.setText(content);
			}
            // 3.Send email
            Transport.send(message);
		}catch(MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public String getSender() {
		return sender;
	}
	public void setSender(String sender) {
		this.sender = sender;
	}
	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content, int type) {
		this.content = content;
		this.contentType = type;
	}

}
           	

Call mail dispatcher in your code


		/************************Send email*****************************/
	//get the host url especially after you publish your web application
	String rootURL = request.getRequestURL().toString().replace(request.getRequestURI(), "");
	//String rootURL = request.getContextPath();getRequestURI().replace("/signup", "");
	Thread confirmThread = new Thread(new MailDispatcher(MailUtil.ACCOUNT_ACTIVATION_SENDER,MailUtil.PASSWORD,email,
			MailUtil.ACCOUNT_ACTIVATION_SUBJECT,MailUtil.generateAccountActivationEmail(hashCode, rootURL), MailUtil.HTML_FORMAT));
	confirmThread.start();
           	

Resolving AuthenticationFailedException

Click on this link and click on turn on radio button to allow users to send mail from unknown location. https://www.google.com/settings/security/lesssecureapps