java 不使用客户端授权密码直接用账号密码发送带附件的邮件
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
@Override
public String toString() {
return "EmailConfig{" +
"host='" + host + ''' +
", username='" + username + ''' +
", password='" + password + ''' +
", senderName='" + senderName + ''' +
'}';
}
}
@Autowired
private EmailConfig emailConfig;
/**
发送带附件的邮件
@param from 发件人
@param receive 收件人
@param subject 邮件主题
@param msg 邮件内容
@param filename 附件地址
*/
public void sendMailForFile(String from, String receive, String subject, String msg, String filename){
if (StringUtils.isEmpty(receive)) {
throw new MyException("收件人邮箱号不能为空");
}
//1、创建邮件对象
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
//2、发邮件人邮箱
javaMailSender.setUsername(emailConfig.getUsername());
//3、发邮件人邮箱密码(默认使用客户端的授权码)
javaMailSender.setPassword(emailConfig.getPassword());
//4、设置邮件服务器主机名 SMTP 服务器地址
javaMailSender.setHost(emailConfig.getHost());
//5、SMTP 服务器: 默认端口 换成腾讯云服务器后,需要将端口换成 465
// javaMailSender.setPort(465);
javaMailSender.setPort(25);
//6、//发送邮件协议名称
javaMailSender.setProtocol("smtp");
//7、编码格式
javaMailSender.setDefaultEncoding("UTF-8");
//8、创建连接对象,连接到邮箱服务器
Properties mailProperties = new Properties();
//发送服务器需要身份验证,要采用指定用户名密码的方式去认证
mailProperties.put("mail.smtp.auth", true);
mailProperties.put("mail.smtp.starttls.enable", true);
//9、添加连接对象到邮件对象中
javaMailSender.setJavaMailProperties(mailProperties);
try {
// 得到默认的对话对象
Authenticator a = new Authenticator() {
public PasswordAuthentication getPassw 《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 ordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getPassword());
}
};
MimeMessage message = getMimeMessage(mailProperties,a,emailConfig.getUsername(),from, receive, subject, msg, filename);
javaMailSender.send(message);
// 发送消息
// Transport.send(message);
System.out.println("Sent message successfully....");
} catch (Exception e) {
e.printStackTrace();
log.error("发送失败{}",e.getMessage());
}
}
private MimeMessage getMimeMessage(Properties props,Authenticator a ,String from,String fromEmail, String receive, String subject, String msg, String filename) throws MessagingException, UnsupportedEncodingException {
// 创建默认的 MimeMessage 对象
//创建 Session 实例
Session session = Session.getDefaultInstance(props, a);
session.setDebug(true);
//创建 MimeMessage 实例对象
MimeMessage message=new MimeMessage(session);
//设置自定义发件人昵称
String nick="";
try {
// nick=javax.mail.internet.MimeUtility.encodeText("luminescience");
if(StringUtil.isNotNull(fromEmail)){
nick=javax.mail.internet.MimeUtility.encodeText(fromEmail);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setFrom(new InternetAddress(nick+" <"+from+">"));
// Set From: 头部头字段
// message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
评论