发送电子邮件,使用身份验证器创建新会话
/**来自 N o w J a v a . c o m**/ //package com.nowjava; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class Main {/*来自 NowJava.com - 时代Java*/ public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException { // sets SMTP server properties Properties properties = new Properties(); properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", port); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.user", userName); properties.put("mail.password", password); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }; Session session = Session.getInstance(properties, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(userName)); String[] recipientArray = recipient.split(","); InternetAddress[] toAddresses = new InternetAddress[recipientArray.length]; for (int i = 0; i < recipientArray.length; i++) { toAddresses[i] = new InternetAddress(recipientArray[i]); } //InternetAddress[] toAddresses = { new InternetAddress(recipient),new InternetAddress("tgbadorrek@gmail.com") }; msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart();