go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  How to send email from a Java app using Gmail?
 
Subject: How to send email from a Java app using Gmail?
Author: WebSpider
Posted on: 08/19/2012 03:15:56 PM


/**
 *   A working example to send out email through Google SMTP server via TLS/StatTLS  
 */

package org.example.sendmail;

import java.util.Properties;
 
import javax.mail.Message; 
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class SendMailTLS {
 
	public static void main(String[] args) {
 
		// SMTP server information
		final String host = "smtp.gmail.com";
		final int port = 487;
		final String username = "username@gmail.com";
		final String password = "password";
 
		// email information
		String from = "email-from@gmail.com";
		String to   = "email-to@gmail.com";
		
		// Step 1) get the connection by authentication via TLS/StartTLS
		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");
		Session session = Session.getInstance(props,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  }
		);
 
		// Step 2) send email 
		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.setRecipient(Message.RecipientType.TO,
				new InternetAddress(to));
			message.setSubject("Testing Subject");
			message.setText("Testing message");

			Transport.send(message);
 
 			System.out.println("A message has been sussessfully sent to: '" + to + "'");
 
		} catch (MessagingException e) {
                        e.printStackTrace();
                        System.out.println("Error in sending email: " + e.toString());
		}
	}
}

Replies:


References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.