Maven+SSM框架实现简单邮件的发送
程序员文章站
2022-07-08 12:09:54
...
准备工作:
1.开启你的qq邮箱的pop3/smtp服务
2.获取你的qq邮箱第三方登陆的授权码
具体步骤:
1.用电脑登陆你的qq邮箱点击设置
2.点击账户
3.往下找,找到如下选项,如果你的qq有密保需要验证才能开启,开启之后点击生成授权码
4.如果你的qq有密保,需要验证才能获取,获取之后就ok了。用手机拍个照记录一下你的授权码,java代码中需要用到哦。
maven中相关包的依赖地址:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
实现:
1.封装账号密码的类
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Authenticator extends Authenticator {
String userName = null;
String password = null;
public Email_Authenticator() {
}
public Email_Authenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
2.发送邮件的类(附有main方法,测试完自行删除即可)
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Sendmail {
public static void main(String[] args) {
try {
send_email("要发送的邮箱地址","测试","你好!");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void send_email(String toEmail,String subjects,String contents) throws IOException, AddressException, MessagingException{
String to = toEmail;
String subject = subjects;
String content = contents;
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.qq.com");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Email_Authenticator("你的qq邮箱", "你的qq邮箱第三方登陆授权码");
javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
MimeMessage mailMessage = new MimeMessage(sendMailSession);
mailMessage.setFrom(new InternetAddress("你的qq邮箱"));
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mailMessage.setSubject(subject, "UTF-8");
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
html.setContent(content.trim(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
}
}
上一篇: springboot获取src/main/resource下的文件
下一篇: Git如何切换账户