首先,要想自动发邮件必须有一个jar包:com.sun.mail:javax.mail:1.4.7
然后要实现一个java工具类,以方便以后使用:
emainUtils:
public void sendMessage(String smtpHost, String from, String fromUserPassword, String to, String subject,
String messageText, String messageType) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true"); // 使用验证
Session mailSession = Session.getInstance(props, new MyAuthenticator(from, fromUserPassword));
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType);
// 第三步:发送消息
// Transport transport = mailSession.getTransport("smtp");
// transport.connect(smtpHost, from, fromUserPassword);
Transport.send(message, message.getRecipients(RecipientType.TO));
}
private class MyAuthenticator extends Authenticator {
String userName = "";
String password = "";
public MyAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
在controller层:
String code = "www.baidu.com";//内容
String content = Constants.EMAIL_PASS[1] + code + Constants.EMAIL_PASS[2];
new EmailUtil().sendMessage(GlobalVars.email_host, GlobalVars.email_username, GlobalVars.email_password,
bought.getAccount()//要发送的账号, Constants.EMAIL_PASS[0]//标题, content, GlobalVars.email_type);
在Constants中:
public static final String[] EMAIL_PASS={"通过审核","登陆地址:","\n如有疑问,请咨询客服!"};
在GlobalVars中:
public static String email_host;
public static String email_username;
public static String email_password;
public static String email_type;
GlobalVars.email_host = properties.getProperty("email_host").trim();
GlobalVars.email_type = properties.getProperty("email_type").trim();
GlobalVars.email_username = properties.getProperty("email_username").trim();
GlobalVars.email_password = properties.getProperty("email_password").trim();
在配置文件中写这四个参数:
email_host=smtp.abc@163.com//前面必须要smtp.
email_username=“”//账号
email_password=“”//密码
email_type=text/html;charset=UTF-8
之后在controller层中添加业务逻辑后,响应后会从abc@163.com网站中自动登陆,将要发送的内容发送给账号(bought.getAccount())。