go to  ForumEasy.com   
JavaPro  
 
 
   Home  |  MyForum  |  FAQ  |  Archive    You are not logged in. [Login] or [Register]  
Forum Home » JavaMail » How to send email from a Java app using Gmail?
Email To Friend  |   Set Alert To This Topic Rewarding Points Availabe: 0 (What's this) New Topic  |   Post Reply
Author Topic: How to send email from a Java app using Gmail?
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 08/19/2012 03:15:56 PM    Edit  |   Quote  |   Report 
How to send email from a Java app using Gmail?

/**
 *   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());
		}
	}
}
 Profile | Reply Points Earned: 0
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 08/19/2012 03:55:24 PM    Edit  |   Quote  |   Report 
Any room to grow? -- holding connection
Essentially, the sending process
       Transport.send(message);

has done the followings inside:

  • Open a connection/session.
  • Send out message.
  • Close the connection.

    As with all client-server architectures, the establishing connection to SMTP server is always the most costing operation. If you have multiple sending tasks during the life cycle of your application, you have want to keep the connection open for future use.

    Here is the variation:
    
    /**
     *   A simple 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);
    			
    			message.saveChanges(); // implicit with send()
    			Transport transport = session.getTransport("smtp");
                            transport.connect();
                            transport.sendMessage(message, message.getAllRecipients());
    
                            // close -- you can keep it open for future use if you have other sending task
                            transport.close();
     
     			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());
    		}
    	}
    }
    
  •  Profile | Reply Points Earned: 0
    WebSpider
    member
    offline   
     
    posts: 147
    joined: 06/29/2006
    from: Seattle, WA
      posted on: 08/19/2012 04:36:47 PM    Edit  |   Quote  |   Report 
    Any problem? -- Gmail SMTP server losing my FROM address in transition
    For the following settings:

                    // authentication
    		final String username = "username@gmail.com";
    		final String password = "password";
     
    		// email information
    		String from = "email-from@myFakeCompany.com";
    		String to   = "email-to@gmail.com";
    


    On the destination (email-to@gmail.com's Inbox):

            from:       username@gmail.com
              to:       email-to@gmail.com
            date:       Sat, Aug 18, 2012 at 10:53 PM
         subject:       Testing Subject
       mailed-by:       gmail.com
    


    OK, my goal is simple -- I want to use Gmail as the third party SMTP server to send my outgoing emails to my clients. But when the email reaches its destination, my email's FROM address has been lost and it has been replaced by the email account which was used for authentication.

    So, I really want to let my clients to get the impression that the messages was sent from FROM address: 'email-from@myFakeCompany.com'. How can I achieve my goal?

    Answer: There are 2 solutions:

    1) Use paid third party email services by which you can set your 'form' address whatever you want it to be.

    2) Use Google Apps (there is a free business account with users less than 10).

     Profile | Reply Points Earned: 0
    WebSpider
    member
    offline   
     
    posts: 147
    joined: 06/29/2006
    from: Seattle, WA
      posted on: 08/21/2012 02:11:21 AM    Edit  |   Quote  |   Report 
    Now what? -- after creating a Goolge Apps business account
    I have created a business account via:

    kttp://www.google.com/a/

    on domain: myFakeCompany.com

    With the followin settings
                    // authentication
    		final String username = "email-from@myFakeCompany.com";
    		final String password = "password";
     
    		// email information
    		String from = "email-from@myFakeCompany.com";
    		String to   = "email-to@gmail.com";
    


    I can make all my outgoing emails be seen on destination as:
            from:       email-from@myFakeCompany.com
              to:       email-to@gmail.com
            date:       Sat, Aug 18, 2012 at 10:53 PM
         subject:       Testing Subject
       mailed-by:       gmail.com
    


    OK, I can send out email via my business account -- that's not surprising. But when my client replied my email to 'email-from@myFakeCompany.com', I did not get anything. Now what?
     Profile | Reply Points Earned: 0
    WebSpider
    member
    offline   
     
    posts: 147
    joined: 06/29/2006
    from: Seattle, WA
      posted on: 08/21/2012 09:52:02 PM    Edit  |   Quote  |   Report 
    Set domain DNS MX records point to Gmail
    Generally, here is how email service should work:
    Outgoing mail:
    
                                             +-------------+   
       {Java Apps} -- smtp.gmail.com:587 --> |  Gmail SMTP | ----> {recipient}
                                             +-------------+
    
    
    Imcomming mail:
    
                                             +----------+       +-------------+
       {sender} -- abc@myFakeCompany.com --> | DNS (MX) + ----> | Gmail Inbox |
                                             +----------+       +-------------+
    



    You just need to instruct your domain's DNS to route all email traffic to Gmail by the following MX records:

         MX: @  1 ASPMX.L.GOOGLE.COM.
         MX: @  5 ALT1.ASPMX.L.GOOGLE.COM.
         MX: @  5 ALT2.ASPMX.L.GOOGLE.COM.
         MX: @ 10 ASPMX2.GOOGLEMAIL.COM.
         MX: @ 10 ASPMX3.GOOGLEMAIL.COM.
    

    Note:
  • The ending dot (.) must be there.
  • The @ sign stands for the domain itself.
  • The lower number has the higher priority.
  •  Profile | Reply Points Earned: 0
    WebSpider
    member
    offline   
     
    posts: 147
    joined: 06/29/2006
    from: Seattle, WA
      posted on: 08/22/2012 01:53:59 AM    Edit  |   Quote  |   Report 
    How do I know my DNS settings are OK?
    nslookup is a network administration command-line tool available for many computer operating systems for querying the Domain Name System (DNS) to obtain domain name or IP address mapping or for any other specific DNS record.

    On Windows, you can type the following:
        C:\> nslookup -q=mx myFakeCompany.com
    


    It will show the MX records which have been taken effect.
     Profile | Reply Points Earned: 0
    WebSpider
    member
    offline   
     
    posts: 147
    joined: 06/29/2006
    from: Seattle, WA
      posted on: 08/23/2012 06:10:00 PM    Edit  |   Quote  |   Report 
    Troubeshooting
    1) JavaMail did not support STARTTLS

    
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. to6sm6813268pbc.12
    	at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1020)
    	at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:716)
    	at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:388)
    


    You just need to download mail.jar for the newer version of JavaMail. The given examples work with JavaMail-1.4.5.



     Profile | Reply Points Earned: 0

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