Sending Email via gmail smtp server in JAVA

Solution 1:

Here I am giving some changes, that work fine for me:

Session session = Session.getInstance(props,null);

You instantiate message object as you did. And finally:

Transport transport = session.getTransport("smtp");
String mfrom = "yourGmailUsernameWithout@"// example laabidiraissi 
transport.connect("smtp.gmail.com", mfrom, "thepassword");
transport.sendMessage(message, message.getAllRecipients());

Edit, would you please give me a favor and copy/paste and try this example and show what it displays:

package com.test;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.junit.Test;

public class EmailService {

@Test
public void test(){
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true); // added this line
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.user", "username");
    props.put("mail.smtp.password", "password");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", true);



    Session session = Session.getInstance(props,null);
    MimeMessage message = new MimeMessage(session);

    System.out.println("Port: "+session.getProperty("mail.smtp.port"));

    // Create the email addresses involved
    try {
        InternetAddress from = new InternetAddress("username");
        message.setSubject("Yes we can");
        message.setFrom(from);
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("receivermail"));

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart("alternative");

        // Create your text message part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("some text to send");

        // Add the text part to the multipart
        multipart.addBodyPart(messageBodyPart);

        // Create the html part
        messageBodyPart = new MimeBodyPart();
        String htmlMessage = "Our html text";
        messageBodyPart.setContent(htmlMessage, "text/html");


        // Add html part to multi part
        multipart.addBodyPart(messageBodyPart);

        // Associate multi-part with message
        message.setContent(multipart);

        // Send message
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com", "username", "password");
        System.out.println("Transport: "+transport.toString());
        transport.sendMessage(message, message.getAllRecipients());


    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

Solution 2:

Ok. It is a little more complex than i tought for the first time... To summorize what i got:

  • There is a very useful command: session.setDebug(true);. If you set this true, every important process will be debuged to the console. I recommend to use it.
  • The second computer could only work with the secure option, you can switch this one with: Transport transport = session.getTransport("smtps"); rather of the non secure smtp... The JavaMail API Transport object will also take care of the ports (respectively smtp: 587, smtps: 465)
  • You can use also the static method of the Transport class for sending the message and (saving it before, non static sendMessage method will not save the message), but this time you need to use the javax.mail.Authenticator at the session creation, like this:

    Session session = Session.getInstance(props,         new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("login", "password");
        }
    

    });

1.4.2 JavaMailApi has another Exception than 1.4.7 version for this issue...

If you don't use it, you can not authenticated with the static method. If you use the instance method, you can.

  • One computer has maven and got the 1.4.2 version of the JavaMail API. Second computer has a downloaded library, with version 1.4.7, which i guess also mess with the things
  • First comp Netbeans, second comp Intellij... +1) There are a lot of old, and bad example code at the internet, which makes harder to use this API properly.

So pretty messed up, but there were some basic concept which should be focused...

Solution 3:

I could reproduce the behaviour described in your question and fix it.

The send method gets stuck at

SMTPTransport(Service).connect(String, int, String, String) line: 308   

The connection does not succeed because you have the wrong port for the gmail smtp host: 465

change it to 587

props.put("mail.smtp.port", "587");

and it will work.

Solution 4:

Using Simple Java Mail it should be straightforward:

Email email = new Email();

email.setFromAddress("lollypop", "[email protected]");
email.addRecipient("C.Cane", "[email protected]", RecipientType.TO);
email.setText("We should meet up!");
email.setTextHTML("<b>We should meet up!</b>");
email.setSubject("hey");

new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);

If you have two-factor login turned on, you need to generate an application specific password from your Google account.