java发送邮件
引入两个包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
正文:
package Com.Ren.Mail;
import com.sun.mail.util.MailSSLSocketFactory;
import org.junit.Test;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class SendMail02 {
@Test
public void sendMail() throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com"); //设置QQ邮件服务器
properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//关于qq邮箱,还要设置SSL加密,加上一下代码即可
MailSSLSocketFactory sf = new MailSSLSocketFactory();
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//javaMail发送邮件的五个步骤
//1. 创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人姓名,授权码
return new PasswordAuthentication("2399296974@qq.com", "hulxblvgclzjecaa");
}
});
//开启Session的debug模式,这样就可以查看到程序发送email的运行状态
//2. 通过Session得到transport对象
Transport transport = session.getTransport();
//3. 使用邮箱的用户名和授权码连接上邮件服务器
transport.connect("smtp.qq.com","2399296974@qq.com", "hulxblvgclzjecaa");
//4. 创建邮件
MimeMessage mimeMessage = new MimeMessage(session);
//指明邮件的发件人
mimeMessage.setFrom(new InternetAddress("2399296974@qq.com"));
//指明邮件的收件人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("renqingbo0@gmail.com"));
//指明邮件标题
mimeMessage.setSubject("欢迎你");
//邮件的文本内容
mimeMessage.setContent("<h1>ni hao1</h1>","text/html;charset=utf-8");
//准备图片数据
MimeBodyPart img = new MimeBodyPart();
//图片数据处理
DataHandler dataHandler = new DataHandler(new FileDataSource("F:\\javacode\\FileUpload\\src\\main\\resources\\1.jpg"));
img.setDataHandler(dataHandler);
img.setContentID("bz.jpg");
//正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一个带图片<img src = 'cid:bz.jpg'>的文件","text/html;charset=utf-8");
//将各个模块加入到总模块中
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(img);
mimeMultipart.addBodyPart(text);
mimeMultipart.setSubType("related");
//将总模块加入到消息中
mimeMessage.setContent(mimeMultipart);
mimeMessage.saveChanges();
//5. 发送邮件
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
//关闭连接
transport.close();
}
}