JavaMail: Send Mail Using Gmail’s SMTP Server

Sometimes having our own SMTP server can cause problems especially the newbie ones. If our SMTP server is being detected by such spam security sites like Spamhaus as a probable spam server, emails that we send to recipients will eventually be blocked. We would have to register our server to these sites so that they would get unblocked. If you are too lazy to wait or want to avoid the hassle of this kind of dilemna, you can actually use GMail’s SMTP server.

The code below sends an email using JavaMail, Java’s mail technology API to send and receive emails. It also includes a Reply-To Email parameter in case you want your Reply-To email address to be different. The other parameter option is to specify if you want to email to be sent at text or HTML. Just input html as the value if you want to send the email as HTML.

public static boolean send(String replyTo, String from_email, String from_name, String to_email, String subject, String body, String type, String bcc_email) {
	boolean sent = false;
	try {
		Properties prop = new Properties();
		prop.put("mail.smtp.port", "25");
		prop.put("mail.smtp.socketFactory.fallback", "false");
		prop.put("mail.smtp.quitwait", "false");
		prop.put("mail.smtp.host", "smtp.gmail.com");
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.starttls.enable", "true");

		Session session = Session.getDefaultInstance(prop);

		String username = (String) prop.get("gmail.username");
		String password = (String) prop.get("gmail.password");

		Message msg = new MimeMessage(session);
		msg.setSubject(subject);

		InternetAddress from = new InternetAddress(from_email, from_name);
		InternetAddress to = new InternetAddress(to_email);
		msg.addRecipient(Message.RecipientType.TO, to);

		// add bcc if not null
		if ((bcc_email != null) && (!bcc_email.equals("")))  msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc_email));

		msg.setFrom(from);

		// set reply to email address
		InternetAddress[] replyToAddress = new InternetAddress[1];
		replyToAddress[0] = new InternetAddress(replyTo);
		msg.setReplyTo(replyToAddress);

		Multipart multipart = new MimeMultipart("related");

		BodyPart htmlPart = new MimeBodyPart();
		if (type.equals("html")) htmlPart.setContent(body, "text/html");
		else htmlPart.setContent(body, "text/plain");

		multipart.addBodyPart(htmlPart);
		msg.setContent(multipart);

		Transport transport = session.getTransport("smtp");
		transport.connect(GMAIL_USERNAME, GMAIL_PASSWORD);
		transport.sendMessage(msg, msg.getAllRecipients());
		transport.close();

		sent = true;
		System.out.println("[MailTool] mail sent successfully ...");

	 } catch (Exception e) {
		 System.err.println("[MailTool] send() : " + e.getMessage());
		 e.printStackTrace();
	 }

	 return sent;
}

Note that connecting to GMail’s SMTP server requires you to authenticate first so you would have to use a GMail account before transactions push through.

Related Posts Plugin for WordPress, Blogger...

tags: , ,

  1. 8 Responses to “JavaMail: Send Mail Using Gmail’s SMTP Server”

  2. Problem is with InternetAddress(from_email, from_name)

    It doesn’t show from_email in recipient’s mail box, shows user gmail address.

    By Bhaskar Roy on Jan 8, 2009

  3. hi bhaskar, im confused. the recipient’s email address is shown instead of the sender’s email address?

    can you please paste the code here how you called the method? maybe the values were not placed correctly according to the parameter ordering

    By tech on Jan 8, 2009

  4. Hello mesg send For Test

    By indranilKundu on Jan 12, 2009

  5. Nice post..Keep them coming :) Thanks for sharing.

    By Nulled Scripts on Dec 22, 2009

  6. change bcc for bcc_mail :)

    By alvaro01 on Oct 24, 2010

  7. @alvaro01: thanks for pointing out this typo ;)

    By tech on Oct 24, 2010

  8. Thanks alot for your help.
    Your tutorial really helpful.
    Good job guy.

    By Mr Big on Sep 15, 2011

  9. @mr big: thanks

    By tech on Sep 15, 2011

Post a Comment

Anti-Spam Protection by WP-SpamFree

Spam protection by WP Captcha-Free