1.java发送邮件:
maven依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
配置:
mail:
#smtp服务主机 qq邮箱则为smtp.qq.com,126邮箱为smtp.126.com,163邮箱为163.smtp.com
smtp:
auth: true
host: smtp.qq.com
user: 邮箱
password: 邮箱授权码
from: XXX网
subject: XXX网会员邮箱注册验证码
content: 尊敬用户:<br> 你好!XXX网会员邮箱注册验证码为:%code%,十分钟内有效。
verify:
code:
length: 6
regex: ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
代码
@Value("${mail.smtp.auth}")
private String mailSmtpAuth;
@Value("${mail.smtp.host}")//发送邮件的服务器 126邮箱为smtp.126.com,163邮箱为163.smtp.com,QQ为smtp.qq.com
private String mailSmtpHost;
@Value("${mail.user}")//发件人邮箱地址
private String mailUser;
@Value("${mail.password}")//发件人邮箱客户端授权码
private String mailPassword;
@Value("${mail.subject}")//邮件主题
private String mailSubject;
@Value("${mail.content}")//邮件内容
private String mailContent;
@Value("${mail.verify.code.length}")
private String vcodeLength;//验证码长度
@Value("${mail.regex}")
private String mailRegex;//邮箱格式正则表达式
/**
* 发送邮箱
* @param to
* @param content
* @throws MessagingException
*/
private void sendMail(String to, String content) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.auth", mailSmtpAuth);
props.put("mail.smtp.host", mailSmtpHost);
props.put("mail.user", mailUser);// 发件人的账号
props.put("mail.password", mailPassword);//发件人的密码
Authenticator authenticator = new Authenticator() {
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailUser, mailPassword);
}
};
//创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
MimeMessage message = new MimeMessage(mailSession);// 创建邮件消息
message.setFrom(new InternetAddress(mailUser));// 设置发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));// 设置收件人
message.setSubject(mailSubject); // 设置邮件标题
message.setContent(content, "text/html;charset=UTF-8"); // 设置邮件的内容体
Transport.send(message);// 发送邮件
}