java 发送邮件
核心依赖 java mail
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>
java 代码
// 发送邮件配置
public static Properties getProperties() {
Properties p = new Properties();
Properties prop = new Properties();
try {
// 相对路径
prop.load(StorageEngine.class.getResourceAsStream("/配置文件.properties"));
} catch (IOException e1) {
e1.printStackTrace();
}
// 端口号
String host = prop.getProperty("email.host");
String port = prop.getProperty("email.port");
String from = prop.getProperty("email.from");
p.put("mail.smtp.host", host);// 可以直接在这里配置发送邮件的port,host
p.put("mail.smtp.port", port);
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.from", from);
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e) {
e.printStackTrace();
logger.error(方法运行异常", e);
}
p.put("mail.smtp.ssl.enable", "true");
p.put("mail.smtp.ssl.socketFactory", sf);
return p;
}
下一步 设置账户密码属性
`private static class MyAuthenticator extends Authenticator {
String userName = null;
String password = null;
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
// 发送邮件的方法
、、 yx收件人 邮箱 fsnr发送内容,fsbt 主题
protected static boolean sendHtmlMail(String yx, String fsnr, String fsbt) {
MyAuthenticator authenticator = null;
Properties pro = getProperties();
Properties prop = new Properties();
try {
prop.load(StorageEngine.class.getResourceAsStream("/配置文件.properties"));
} catch (IOException e1) {
e1.printStackTrace();
}
String username = prop.getProperty("email.username");
String password = prop.getProperty("email.password");
authenticator = new MyAuthenticator(username, password);
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
Boolean result = true;
try {
javax.mail.Message mailMessage = new MimeMessage(sendMailSession);
mailMessage.addFrom(InternetAddress.parse(username));
// 收件人
Address to = new InternetAddress(yx);
mailMessage.setRecipient(javax.mail.Message.RecipientType.TO, to);
mailMessage.setSentDate(new Date());
// 主题
mailMessage.setSubject(fsbt);
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
// 发送内容
html.setContent(fsnr, "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
} catch (MessagingException ex) {
ex.printStackTrace();
logger.error(方法运行异常", ex);
result = false;
}
return result;
}
注意:1测试使用时可以不读取配置文件,直接在代码中写好发送邮件的账户密码
2 代码有重复部分,可复用,可以优化。
3 下面是自己写的一个邮件测试
https://download.csdn.net/download/qq_40877660/10783060