-
StackOverflow 文档
-
java-ee 教程
-
Javamail API
-
发送简单电子邮件
public class GoogleMailTest {
GoogleMailTest() {
}
public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
GoogleMailTest.Send(username, password, recipientEmail, "", title, message);
}
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.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");
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));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
JOptionPane.showMessageDialog(null, msg.getSize());
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(title);
msg.setText(message);
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}
// And use this code in any class, I'm using it in the same class in main method
public static void main(String[] args) {
String senderMail = "inzi769@gmail.com"; //sender mail id
String password = "769inzimam-9771"; // sender mail password here
String toMail = "inzi.rogrammer@gmail.com"; // recepient mail id here
String cc = ""; // cc mail id here
String title = "Java mail test"; // Subject of the mail
String msg = "Message here"; // message to be sent
GoogleMailTest gmt = new GoogleMailTest();
try {
if (cc.isEmpty()) {
GoogleMailTest.Send(senderMail, password, toMail, title, msg);
} else {
GoogleMailTest.Send(senderMail, password, toMail, cc, title, msg);
}
} catch (MessagingException ex) {
Logger.getLogger(GoogleMailTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}