Sending mail using JavaMail APIs

In this example Google SMTP server is used to send email.


import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import java.util.Properties;


public class Email {
	String email = "your_id@gmail.com", password = "your_password",
			host = "smtp.gmail.com", port = "465";

	public Email() {
	}

	public void sendEamil(String m_to, String m_subject, String m_text) {
		Properties props = new Properties();
		props.put("mail.smtp.user", email);
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.auth", "true");
		// props.put("mail.smtp.debug", "true");
		props.put("mail.smtp.socketFactory.port", port);
		props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		SecurityManager security = System.getSecurityManager();
		try {
			Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getInstance(props, auth);
			session.setDebug(true);
			MimeMessage msg = new MimeMessage(session);
			msg.setText(m_text);
			msg.setSubject(m_subject);
			msg.setFrom(new InternetAddress(email));
			msg.addRecipient(Message.RecipientType.TO,new InternetAddress(m_to));
			Transport.send(msg);
		} catch (Exception mex) {
			mex.printStackTrace();
		}
	}

	private class SMTPAuthenticator extends Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(email, password);
		}
	}
}

You May Also Like

12 Comments

  1. I also have a writeup that presents my EmailDelivery class (and example of how to use it) which I wrote to help me easily send emails from my Java applications using JavaMail. It supports relaying through SMTP servers that require authentication and has convenience methods for easily adding file attachments.

    Check it out at:
    http://timarcher.com/?q=node/53

  2. Absolutely fine and working good. But the given is the code for sending emails. But can you provide us the code for getting the attachment name in case if the mail is bounced back.

    TONS OF THANKS IN ADVANCE

  3. thats great!

    just 10 minutes earlier i was assigned a task to know and configure java-mail.
    i used your post, and done it in less than 10 mins.

    thank you so much.

  4. DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth false
    DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:

    this is wat i m getting
    can you help me out….

  5. hi,
    i dont know exactly what code you are composing. my code is as follow, plz check, it might help you.

    public class JavaMail {
    String
    from_email = “asifsh7@gmail.com”,
    password = “mypassword”,
    host = “smtp.gmail.com”,
    port = “465”;

    Properties props = new Properties();

    public JavaMail(){
    props.put( “mail.smtp.user”, from_email );
    props.put( “mail.smtp.host”, host );
    props.put( “mail.smtp.port”, port );
    props.put( “mail.smtp.starttls,enable”, “true” );
    props.put( “mail.smtp.auth” , “true” );
    props.put( “mail.smtp.socketFactory.class” ,”javax.net.ssl.SSLSocketFactory” );
    props.put( “mail.smtp.socketFactory.fallback” , “false” );
    }

    public void sendEmail(String m_to, String m_subject, String m_text){
    SecurityManager security = System.getSecurityManager();

    try{
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props,auth);

    session.setDebug(true);
    MimeMessage msg = new MimeMessage (session);
    msg.setText(m_text);
    msg.setSubject(m_subject);
    msg.setFrom(new InternetAddress(from_email));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
    Transport.send(msg);
    }catch(Exception exp){
    exp.printStackTrace();
    }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator
    {
    public PasswordAuthentication getPasswordAuthentication(){
    return new PasswordAuthentication(from_email, password);
    }
    }

    public static void main( String arg[] ) {
    JavaMail mail = new JavaMail();
    mail.sendEmail(“asifshahzad@seantechsoft.com”, “subject here”, “msg body here ….”);
    }
    }

  6. shriram;

    Initially I also got some relevant problem like you have. That I was unable to connect with SMTP server. I found my AntiVirus stopping my connection with it. You can check you Antivirus settings for this.

    Check your code again by commenting props.put( “mail.smtp.port”, port ); I think it will/should use default port 25. Not full sure but give it a try and share your findings.

  7. hi All.. i am getting the same exception as mentioned by shriram..
    the solution proposed by tahir..//commenting the props.put( “mail.smtp.port”, port ); is taking the default port as 25.. but it is gining me the same exception.. the complete stack trace is as follows..

    DEBUG: JavaMail version 1.4ea
    DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.5.0_03\lib\javamail.providers (The system cannot find the file specified)
    DEBUG: !anyLoaded
    DEBUG: not loading resource: /META-INF/javamail.providers
    DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
    DEBUG: Tables of loaded providers
    DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
    DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
    DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
    DEBUG: !anyLoaded
    DEBUG: not loading resource: /META-INF/javamail.address.map
    DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.5.0_03\lib\javamail.address.map (The system cannot find the file specified)
    DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 25, isSSL false
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at GoogleTest.sendSSLMessage(GoogleTest.java:70)
    at GoogleTest.main(GoogleTest.java:27)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    … 8 more

    Please help!!!!!!!

  8. Hi all,
    Thanx a ton for the load of information.
    I was wondering if it is possible to go through the content of an email without actually having to open the message and then retrieve certain info out of them (eg. embedded URLs).
    If so, can someone please help me out with the code for the same.
    Thanks in advance,

  9. Hi Kapil,
    Yes it is possible. What you have to do is:
    1. Get the Inbox Folder

    store = session.getStore( mailProps.getProperty( “MAIL_PROVIDER” ) );
    store.connect( “mail.gmail.com”, “login”, “password” ) ;
    inbox = store.getFolder( “INBOX” ) ;
    inbox.open( Folder.READ_ONLY ) ;

    2. Get Messages fron InBox
    Message[] messages = null ;
    messages = inbox.getMessages() ;

    3. Iterate through each Message in messages array, read the Message Content section
    for ( int i = 0; i < messages.length; i++ )
    {
    if (messages[i].getContentType().equals(“text/plain”))
    {
    String content = (String)messages[i].getContent();
    // HERE APPY SOME STRING MATCHING PATTERN TO MATCH THE URL YOU ARE LOOKIN FOR INSIDE MAIL BODY, WHERE YOU FIND THE MATCH, … READ THAT URL …
    }

    if( messages[i].getContent() instanceof Multipart )
    { // ITS MEAN YOUR MESSAGE IS MULTIPART, WHICH SHOWS IT HAS SOME ATTACHMENTS ALSO, SO YOU NEED TO WRITE LOGIC TO PARSE MULTIPART MESSAGE.
    }
    }

    I hope you get the idea, and will extend the above code to write parser for multipart messages. Then you will be ready to parse both messages body/content (plain messages, attachment message), and identify the embedded URLs inside them.

    Regards!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.