一个Java发送邮件的案例
经常有些要发送邮件的需求,但是去网上拷代码老是拷不到能直接运行的,还经常要去以前的项目里面拷,今天直接发出来算了,免得每次都要去别的项目拷。
(只支持发送简单的文本文件,发附件的稍微复杂一丢丢,这里就不贴出来了)
依赖:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
源代码:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendIdentifyingCode {
public SendIdentifyingCode(String address, String content) {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
//用465端口
prop.setProperty("mail.smtp.port", "465");
prop.setProperty("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(prop);
session.setDebug(true);
Transport ts = null;
try {
ts = session.getTransport();
//下面这行自己用自己的噢,最后那个参数在我下面那个图里面开启点两下就可以找到了
ts.connect("smtp.qq.com", "ohgreenorangestack@foxmail.com", "xxxxxxxxxxx");
Message message = createSimpleMail(session, address, content);
ts.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
} finally {
try {
assert ts != null;
ts.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
private MimeMessage createSimpleMail(Session session, String address, String content) throws MessagingException {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("ohgreenorangestack@foxmail.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
message.setSubject("FaceProcessor验证消息");//邮件标题
message.setContent(content, "text/html;charset=UTF-8");//支持html格式
return message;
}
}
这边用的QQ邮箱
端口报错的话就用25,但是云服务器不让你用25端口,465端口是用的SSL,用这端口屁事比较多,jdk版本稍微高一点的话把SSL禁用了
解决方案https://blog.csdn.net/ooblack/article/details/119300423
然后要是能用25的话尽量用25得了,但是云服务器去申请25解封通过率不高
贴一个各个邮箱对应的端口
https://www.cnblogs.com/ni-huang-feng-wu/p/14773917.html
SpringBoot又把这玩意又封装了一次,如果是Spring忠实粉丝的话可以去用SpringBoot的
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.5.6</version>
</dependency>
接下来怎么写自行百度。