java发送QQ邮件-qq邮箱怎么发送文件夹

首先要开启QQ邮箱SMTP/POP3服务 获取秘钥 为emaillPass

写在配置文件中

emailPass=XXXXXXXX
hosts=smtp.qq.com
fromAddress=XXXXXX@qq.com
emailusername=XXXXXXdada

代码如下:

package com.zk.shop.utils;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.sun.mail.util.MailSSLSocketFactory;
/**
* JavaMail发送邮件:前提是QQ邮箱里帐号设置要开启POP3/SMTP协议
*/
@Component
public class SimpleMailSender {
@Value("${fromAddress}")
private String fromAddress;
@Value("${emailusername}")
private String emailusername;
@Value("${emailPass}")
private String emailPass;
@Value("${hosts}")
private String hosts;
public void main(String[] args) throws Exception {
}
public boolean sendMSG(String type, String emailTo, String UUID) {
try {
Properties prop = new Properties();
// 开启debug调试,以便在控制台查看
// prop.setProperty("mail.debug", "true");
// 设置邮件服务器主机名
prop.setProperty("mail.host", "smtp.qq.com");
// 发送服务器需要身份验证
prop.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
prop.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 创建session
Session session = Session.getInstance(prop);
// 通过session得到transport对象
Transport ts = session.getTransport();
// 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
System.out.println("emailusername=" + emailusername);
ts.connect(hosts, emailusername, emailPass);// 后面的字符是授权码
// 创建邮件
Message message = createSimpleMail(type, emailTo, UUID, session);
// 发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* @Method: createSimpleMail
* @Description: 创建一封只包含文本的邮件
*/
public MimeMessage createSimpleMail(String type, String emailTo, String UUID, Session session) throws Exception {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress(fromAddress));
// 指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
// 邮件的标题
message.setSubject("修改密码");
// 邮件的文本内容
if ("create".equals(type))
message.setContent("尊敬的用户,您正在尝试注册帐号,请将后面内容复制到验证栏:" + UUID + "\n如不是本人操作,请勿将验证码发送给他人!!!", "text/html;charset=UTF-8");
else if ("reset".equals(type))
message.setContent("尊敬的用户,您正在尝试修改密码,请将后面内容复制到修改密码处:" + UUID + "\n如不是本人操作,请勿将验证码发送给他人!!!", "text/html;charset=UTF-8");
// 返回创建好的邮件对象
return message;
}
}

收到的邮件如下

java发送QQ邮件

推荐阅读