废话不多说 直接上代码 自个耍↓↓↓
package com.example.demo.util;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* DATE: 2023/9/1
* Author: Alun
*/
public class EmailUtil {
public static void sendEmail(String host, String port, final String username, final String password,
String toAddress, String subject, String message, String attachmentPath) throws MessagingException {
// 设置邮件属性
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// 创建会话对象
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息
Message emailMessage = new MimeMessage(session);
emailMessage.setFrom(new InternetAddress(username));
emailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
emailMessage.setSubject(subject);
// 创建消息体部分
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message);
// 创建附件部分
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(attachmentPath);
// 创建多部分消息
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentPart);
// 设置消息内容
emailMessage.setContent(multipart);
// 发送邮件
Transport.send(emailMessage);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
System.out.println("邮件发送失败!");
throw e;
}catch (Exception e){
System.out.println("附件添加失败!");
throw e;
}
}
}
package com.example.demo;
import com.example.demo.util.EmailUtil;
import javax.mail.MessagingException;
/**
* DATE: 2023/9/1
* Author: Alun
*/
public class EmailText {
public static void main(String[] args) {
//个别参数晚上一大把 直接百度
String host = "smtp.example.com"; // SMTP服务器地址
String port = "587"; // SMTP服务器端口
String username = "your_email@example.com"; // 发件人邮箱
String password = "your_password"; // 发件人邮箱密码
String toAddress = "recipient@example.com"; // 收件人邮箱
String subject = "测试邮件"; // 邮件主题
String message = "这是一封测试邮件。"; // 邮件内容
String attachmentPath = "path_to_attachment_file"; // 附件文件路径
try {
EmailUtil.sendEmail(host, port, username, password, toAddress, subject, message, attachmentPath);
} catch (MessagingException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}
本人用163邮箱测试的,常见报错问题如下:
类似这种问题 说明已经成功了一半 还需设置一下163客户端授权码
开启成功后 会发送 "成功开启IMAP/SMTP服务,在第三方客户端登录时,登录密码输入以下授权密码" 然后把改密码复制粘贴到 对应测试类中的password(发件人密码)! 以下就是成功发送后 返回结果
校验是否成功 还可以去邮箱查看 已发送 就能找到对应发送 邮件~~~~