Java code to send Email through Gmail SMTP Server using Java Mail

                The following code sends e-mail using by JavaMail through gmail server. JavaMail 1.4 is capable of sending and reading messages using Gmail. For security reasons, GMail allows SMTP access over an SSL connection. Please download Javamail 1.4 jar (java-mail-1.4.jar)  and include in the Classpath. 
       As far as Yahoo mail is concerned, Free Yahoo! Mail accounts do not allow POP3 or SMTP access. You must purchase a Yahoo! Mail Plus account to get POP3 and SMTP access. Now let us see the java code to send email through Gmail SMTP server.  Create both classes (SendEmailTest, SendMail) given below  in a single java file. 
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPSSLTransport;

public class SendEmailTest {

public static void main(String[] args) {

String from = ""; //your gmail id which is used to send mail

String to = "";   // receivers email id
String subject = "Test Message";
String message = "This is a test message sent via Gmail ";
SendMail sendMail = new SendMail(from, to, subject, message);
class SendMail {
private String from;
private String to;
private String subject;
private String text;

public SendMail(String from, String to, String subject, String text)
this.from = from; = to;
this.subject = subject;
this.text = text;

public void send()
String host = "";
String userid = "Your Gmail Id";
String password = "Your Gmail Password";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("", host);
props.setProperty("mail.transport.protocol", "smtps");
props.put("mail.smtp.user", userid);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "465");
props.put("mail.smtps.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;

try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {


message.setRecipient(RecipientType.TO, toAddress);

//SMTPSSLTransport transport =(SMTPSSLTransport)session.getTransport("smtps");

Transport transport = session.getTransport("smtps");
transport.connect(host, userid, password);
transport.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e) {

Leave a Reply