How to Send an Email by Java Application Using Gmail, Yahoo, or Hotmail

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.

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

Trouble sending email to hotmail using javamail

You can try using sendgrid. I just tested it out and if you use legitimate email addresse for the from, it seems to work.

    import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;

public class SimpleMail {

private static final String SMTP_HOST_NAME = "smtp.sendgrid.net";
private static final String SMTP_AUTH_USER = "sendgrid-username";
private static final String SMTP_AUTH_PWD = "sendgrid-password";

public static void main(String[] args) throws Exception{
new SimpleMail().test();
}

public void test() throws Exception{
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", 587);
props.put("mail.smtp.auth", "true");

Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
// uncomment for debugging infos to stdout
// mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);

Multipart multipart = new MimeMultipart("alternative");

BodyPart part1 = new MimeBodyPart();
part1.setText("Checking to see what box this mail goes in ?");

BodyPart part2 = new MimeBodyPart();
part2.setContent("Checking to see what box this mail goes in ?", "text/html");

multipart.addBodyPart(part1);
multipart.addBodyPart(part2);

message.setContent(multipart);
message.setFrom(new InternetAddress("actual@emailaddress-goeshere.com"));
message.setSubject("Can you see this mail ?");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("person@tosendto.com"));

transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}

private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}

Using javamail to send from hotmail?

1) use debug output:

session.setDebug(true);

2) hotmail smtp server starts non-ssl connection on port 25 or 587, and uses starttls after initial connection; thus remove lines

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

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

3) mimimum amount of settings is then:

    props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.live.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");

this assumes port is 25, otherwise add props.put("mail.smtp.port", "587");

4) yet even nicer looks this:

    ...
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props);
Transport trans = session.getTransport("smtp");
trans.connect("smtp.live.com", 25, "user", "pass");

now you're connected, use methods of Transport

How do I send an e-mail in Java?

Here's my code for doing that:

import javax.mail.*;
import javax.mail.internet.*;

// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);

// Construct the message
String to = "you@you.com";
String from = "me@me.com";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Hi,\n\nHow are you?");

// Send the message.
Transport.send(msg);
} catch (MessagingException e) {
// Error.
}

You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/

How to send an email by Smalltalk application using Gmail / Yahoo / Outlook

You should state which Smalltalk you are using since there are different dialects and all have different ways of handling things like e-mail.

In Pharo, check out the class SMTPClient. There are class methods that have example methods showing how to send e-mails.

For VisualWorks, load the parcel NetClients and check out the classes MailMessage and SMTPClient.

Here's an example of code that sends an e-mail in VisualWorks:

(Net.SMTPClient host: Net.NetClient netSettings defaultOutgoingHost name)
user: Net.NetClient netSettings defaultOutgoingHost netUser;
send: (Net.MailMessage newTextPlain
subject: 'This is the subject';
from: 'my-email@gmail.com';
to: 'your-email@gmail.com';
text: 'This is the body';
yourself).


Related Topics



Leave a reply



Submit