求高手帮忙看下:jsp激活邮箱如何实现?就是系统自动发邮件到客户邮箱!本人刚学是个菜鸟

最好有代码,好的话加分!!谢谢各位啦!拜托啦!
2024-12-15 06:58:38
推荐回答(1个)
回答1:

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);
}
}