这是一个idea里发送简单邮件的模板,后续会更新在项目里如何进行运用。
带附件的暂时不演示。
这属于个小demo,后续还会抽出专门的properties进行存储对应的授权码邮箱等信息,也会封装一个发送邮件的方法,供其他的发送邮件业务调用。
自测获取授权码的方式可以百度一下。将对应的值设置成自己的,就可以发送成功
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;/*** @author liums 邮件简单发送测试流程* @date 2023/6/28 17:29* @description QQemailDemo1*/
public class QQemailDemo1 {public static void main(String[] args) throws Exception {Properties prop = new Properties();prop.setProperty("mail.host","smtp.qq.com"); //设置QQ邮件服务器prop.setProperty("mail.transport.protocol","smtp"); //邮件发送协议prop.setProperty("mail.smtp.auth","true"); //需要验证用户名密码//关于QQ邮箱,还要设置SSL加密,加上以下代码即可MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);prop.put("mail.smtp.ssl.enable","true");prop.put("mail.smtp.ssl.socketFactory",sf);//使用JavaMail发送邮件的5个步骤//1、创建定义整个应用程序所需的环境信息的Session对象Session session = Session.getInstance(prop, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {//发件人邮件用户名、授权码return new PasswordAuthentication("1475494286@qq.com","*************");}});//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态session.setDebug(true);//2、通过session得到transport对象Transport ts = session.getTransport();//3、使用邮箱的用户名和授权码连上邮件服务器 ts.connect("smtp.qq.com","14754294286@qq.com","*************");//4、创建邮件:写邮件//注意需要传递SessionMimeMessage message = new MimeMessage(session);//指明邮件的发件人message.setFrom(new InternetAddress("14754924286@qq.com"));//指明邮件的收件人message.setRecipient(Message.RecipientType.TO,new InternetAddress("huheran07@163.com"));//邮件的标题message.setSubject("这是一封来自未来的邮件,祝现在的我开心,顺遂");//邮件的文本内容message.setContent("<h1 style='color:red'>这是一封来自未来的邮件,祝现在的你开心,顺遂</h1>", "text/html;charset=UTF-8");//5、发送邮件ts.sendMessage(message,message.getAllRecipients());//6、关闭连接ts.close();}
}
依赖:其实只用了一个,我三个都导入了
<!-- 发送邮件相关依赖--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-email</artifactId><version>1.5</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version></dependency>