Wednesday, August 29, 2012

Sending Email Via JavaMail API Example

From last one month, My internet device is missing from my terrace. So, Mostly I use mobile to access my mail but accessing mail via mobile is very irritating thing because of the slow bandwidth. To send one single mail I have to wait till the mailbox get opened.

This is very simple way to send mail without opening your account. :)

This is the example to show you how to use JavaMail API method to send an email via Gmail SMTP server.

You need mail.jar library to run this code.

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;

 * @author abdul
public class SendEmail {

    public static void main(String[] args) {
        final String username="YOUR_USER_NAME"; //abdulwaheed18
        final String password="YOUR_PASSWORD";   //*******

        final String to = "SENDER_EMAIL"; //
        final String from = "YOUR_EMAIL"; //

        Properties props = new Properties();
        props.put("", "");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(to));
            message.setText("Hi User,\n Surprise Message.\n Regards,\nWaheed");
            System.out.println(“Message sent Successfully");
        } catch (MessagingException e) {
            throw new RuntimeException(e);

Gmail SMTP Detail :

1 comment:

  1. The King Casino | Slot Games - Herzaman India
    Pragmatic Play's new online 1xbet app slots are available septcasino on the online casino's website and can be played on your phone from anywhere.


How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...