Sending Email via Gmail Smtp Server in Java

Sending Email via gmail smtp server in JAVA

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();
}
}
}

Java to send an email via gmail

I think you need to use 465 port, and smtps (Not smtp) for transport.

A complete workable code from an open source project :

http://jstock.hg.sourceforge.net/hgweb/jstock/jstock/file/d9290c44d19c/src/org/yccheok/jstock/alert/GoogleMail.java

/**
* Send email using GMail SMTP server.
*
* @param username GMail username
* @param password GMail password
* @param recipientEmail TO recipient
* @param ccEmail CC recipient. Can be empty if there is no CC recipient
* @param title title of the message
* @param message message to be sent
* @throws AddressException if the email address parse failed
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
*/
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");

/*
If set to false, the QUIT command is sent and the connection is immediately closed. If set
to true (the default), causes the transport to wait for the response to the QUIT command.

ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://forum.java.sun.com/thread.jspa?threadID=5205249
smtpsend.java - demo program from javamail
*/
props.put("mail.smtps.quitwait", "false");

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

// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);

// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}

msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());

SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}

How to send email from Web Server using java.mail using Gmail server

Same problem I faced recently, I found problem is of EC2 region. Google does not allow to login less Secure app from a non-frequent location of user. Either you use Google Mail APIs or use some other mail platforms like Yahoo. Check your EC2 instance region. try following code with yahoo mail, Deploy it on Elastic beanstalk or whatever environment you are using. This works for me.

public void yahooSend(String mail,String subject,String msg) {

// Sender's email ID needs to be mentioned
String from = "YOUR_YAHOO_MAIL";
String pass ="YOUR_YAHOO_PASSWORD";
// Recipient's email ID needs to be mentioned.
String to = mail;
String host = "smtp.mail.yahoo.com";

// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
// props.put("mail.smtp.user", "YAHOO_USER_NAME");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");

// Get the default Session object.
Session session = Session.getDefaultInstance(properties);

try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));

// Set Subject: header field
message.setSubject(subject);

// Now set the actual message
message.setText(msg);
System.out.print("Sending msg "+msg);
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host,587, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System. out.println("Sent message successfully....");
}catch (MessagingException mex) {
System. out.print(mex);
mex.printStackTrace();
}
}

Java Send Email via gmail

Your source code is perfect for sending email via gmail. May be you have to allow your account for less secure access via https://www.google.com/settings/security/lesssecureapps

Here is your code. I made very little modification to run as standalone program. It requires two jars : 1) mail-1.4.7.jar and 2) activation-1.1.1.jar

import java.util.Properties;
import java.util.Scanner;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;

/**
* Following jar are required:
* 1) mail-1.4.7.jar from http://central.maven.org/maven2/javax/mail/mail/1.4.7/mail-1.4.7.jar
* 2) activation-1.1.1.jar from http://central.maven.org/maven2/javax/activation/activation/1.1.1/activation-1.1.1.jar
*
*/
public class Test {

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("gmail username: ");
String username = sc.next();
System.out.print("gmail password: ");
String password = sc.next();
System.out.print("destination email address: ");
String to = sc.next();
System.out.print("subject: ");
String subject = sc.next();
System.out.print("email body: ");
String email_body = sc.next();
Test test = new Test();
test.doSendMail(username, password, to, subject, email_body);
sc.close();

}
// sends mail
public void doSendMail(final String username, final String password, String to, String subject, String email_body) {

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(email_body);
Transport.send(message);
System.out.println("message sent");
JOptionPane.showMessageDialog(null, "Message Sent!", "Sent", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
JOptionPane.showMessageDialog(null, e.toString());
}
}
}

Send email via smtp.gmail in Spring Faremework

  1. Go to gmail.com
  2. Click on your profile picture and goto Manage Your account
  3. On the new page, go to the Security tab

    Sample Image
  4. Scroll down and turn-on less secure app access

    Sample Image
  5. Confirm the access in your email(optional, sometimes needed only)

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

First download the JavaMail API and make sure the relevant jar files are in your classpath.

Here's a full working example using GMail.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Main {

private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "lizard.bill@myschool.edu";

public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";

sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);

try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];

// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}

for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}

message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)


Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.



Related Topics



Leave a reply



Submit