How can I send an email by Java application using GMail, Yahoo, or Hotmail?
Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
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 = "[email protected]";
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.
Something like this (sounds like you just need to change your SMTP server):
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Other people have good answers above, but I wanted to add a note on my experience here. I've found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access. The emails I was sending were not spam, but were website "welcome" emails when users registered with my system. So, YMMV, and I wouldn't rely on Gmail for a production webapp. If you're sending email on a user's behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.
Also, if you're using Spring, here's a working config to use Gmail for outbound SMTP:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="defaultEncoding" value="UTF-8"/>
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="465"/>
<property name="username" value="${mail.username}"/>
<property name="password" value="${mail.password}"/>
<property name="javaMailProperties">
<value>
mail.debug=true
mail.smtp.auth=true
mail.smtp.socketFactory.class=java.net.SocketFactory
mail.smtp.socketFactory.fallback=false
</value>
</property>
</bean>
Even though this question is closed, I'd like to post a counter solution, but now using Simple Java Mail (Open Source JavaMail smtp wrapper):
final Email email = new Email();
String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"[email protected]"};
email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");
new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);
My complete code as below is working well:
package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
// Sender's email ID needs to be mentioned
String from = "[email protected]";
String pass ="test123";
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
String host = "smtp.gmail.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);
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("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}