Tov Are Jacobsen
Learn how to send email via Gmail from Java in 120 seconds.
I did a quck google check and found that there where lots of different
snippets out there for sending a simple SSL email.
Here's a short snippet with all the indirections and extras to get
something up'n running fast.
- Example is written for JDK 1.6 (Java 6)
- Download https://maven-repository.dev.java.net/nonav/repository/javax.mail/jars/mail-1.4.1.jar and add it to your classpath (Build path).
- Change the stuff in yellow to your own info.
- Run (Make sure you have enabled pop or imap in you gmail account)
- (Then ... write things from scratch with proper abstraction and exception handling).
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail@tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen@iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin@tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
To easily send off emails I can really recommend using the Apache
Commons package instead http://commons.apache.org/email/ package, it does a
brilliant job in simplifying working with emails.
Happy hacking!