Java 发送QQ邮件
第一步:将发送人的QQ邮箱中的IMAP/SMTP服务打开,并保存授权码
第二步:在IDEA创建一个项目。这里我建的maven项目
第三步:导入jav包。
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
第四步:编写代码
将代码中的String 字符串中的内容改写为自己的即可
private static String agreement_code = "授权码";
private static String from = "发送账号";
private static String to = "接受账号";
核心代码
package com.util;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailTest {
private static String host = "smtp.qq.com";
private static String agreement = "smtp";
private static String auth = "true";
private static String agreement_code = "授权码";
private static String from = "发送账号";
private static String to = "接受账号";
public static void main(String[] args) throws MessagingException {
Properties prop = new Properties();
prop.setProperty("mail.host", host);
prop.setProperty("mail.transport.protocol", agreement);
prop.setProperty("mail.smtp.auth", auth);
Session session = Session.getInstance(prop);
Transport ts = session.getTransport();
ts.connect(host, from, agreement_code);
MimeMessage message = new MimeMessage(session);
//加入发送人
message.setFrom(new InternetAddress(from));
//加入收信人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
//编写内容
message.setSubject("使用Java发送邮件");
message.setContent("<b>你想月薪过万吗?</b></br>你想赢取白富美吗?来学java吧。<h3>实现你的梦想!</h3>", "text/html;charset=utf-8");
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
第五步:运行程序。在接受着邮箱中查看消息