import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public static void postMail(String smtpHost ,String recipients[],String subject,String message ,String from, EmailAuth emailAuth) throws MessagingException{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, emailAuth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
/*msg.setHeader("From","admin@alumni.163.com");
msg.setHeader("Reply-to",from);*/
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++){
try{
addressTo[i] = new InternetAddress(recipients[i]);
}catch(Exception e){
System.out.print( "postMail error"+e);
}
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain;charset=gbk");
Transport.send(msg);
}
这是EmailAuth代码:
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class EmailAuth extends Authenticator {
private String userName = null;
private String password = null;
public EmailAuth(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}