Skip to content

Instantly share code, notes, and snippets.

@srikanthps
Created July 17, 2010 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srikanthps/479631 to your computer and use it in GitHub Desktop.
Save srikanthps/479631 to your computer and use it in GitHub Desktop.
Java app to send emails using "Gmail"
MailerApp.java is a code snippet that I found in the comments section of http://forums.sun.com/thread.jspa?threadID=668779.
It can send emails using your gmail account.
Try it out! Its fun!
import java.security.Security;
import java.util.Properties;
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;
public class MailerApp {
private String mailhost = "smtp.gmail.com";
public synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"your-user-id@gmail.com", "your-gmail-password");
}
});
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setContent(body, "text/plain");
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress
.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
recipients));
Transport.send(message);
}
public static void main(String args[]) throws Exception {
MailerApp mailutils = new MailerApp();
mailutils.sendMail(
"Email Tests",
"Mail sent by a 63 line Java code copied from: http://forums.sun.com/thread.jspa?threadID=668779",
"your-mail-id@gmail.com",
"receiver1@domain1,com,recieever2@domain2.com");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment