web自动发送邮件

           首先,要想自动发邮件必须有一个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())。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值