qq邮箱 实现邮件的发送
*这个也只是在网上看大神实现 学习到了一点
- 使用java实现邮件发送
- 传送文字 当前时间 以及图片
首先建个maven web项目
第一步
qq邮箱需要设置服务
进入邮箱 点击设置
往下面 滑动找到服务 如图
开启第一个pop3服务
这个授权码先保存
第二步
导入邮件发送的二个pom依赖
<!-- 邮件start -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- 邮件end -->
<!-- https://mvnrepository.com/artifact/com.sun.mail/smtp -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>smtp</artifactId>
<version>1.5.2</version>
</dependency>```
第三步
测试方法去测试
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
public class test {
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp"); // 连接协议
properties.put("mail.smtp.host", "smtp.qq.com"); // 主机名
properties.put("mail.smtp.port", 465); // 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true"); // 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true"); // 设置是否显示debug信息 true 会在控制台显示相关信息
// 得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress("发件人邮箱地址@qq.com "));
// 设置收件人地址
//单个
message.setRecipients( Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("收件人邮箱地址@qq.com") });
//多个
message.setRecipients( Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("收件人邮箱地址@qq.com") });
// 设置邮件标题
message.setSubject("由JavaMail发出的测试邮件");
// 设置邮件内容
message.setText("内容为: 这是单发多邮件测试!");
//设置邮件的主题
message.setSubject("你好啊!");
//创建图片
MimeBodyPart img = new MimeBodyPart();
//设置邮件当前的时间
message.setSentDate(new Date());
/*JavaMail API不限制信息只为文本,任何形式的信息都可能作茧自缚MimeMessage的一部分.
* 除了文本信息,作为文件附件包含在电子邮件信息的一部分是很普遍的.
* JavaMail API通过使用DataHandler对象,提供一个允许我们包含非文本BodyPart对象的简便方法.*/
DataHandler dh = new DataHandler(new FileDataSource("src//1.jpg"));
img.setDataHandler(dh);
//创建图片的一个表示用于显示在邮件中显示
img.setContentID("a");
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect("发件人的邮箱账户@qq.com", "刚刚的授权码");// 密码为刚才得到的授权码
message.saveChanges(); //保存修改
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
}
注意:图片的是tomcat 服务器上你保存图片的地址 确保正确