Java 基于JavaMail实现QQ邮件发送(也可实现群发)

1.开启SMTP服务
在 QQ 邮箱里的  设置 -> 账户 里开启 SMTP 服务


注意开启完之后,QQ 邮箱会生成一个授权码,在代码里连接邮箱使用这个授权码而不是原始的邮箱密码,这样可以避免使用明文密码。

2.下载依赖的 jar 包
解压完之后,通常我们只需要其中的 mail.jar ,把它加到  工程的依赖包中。

3.完整代码示例
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;

public class MailTool {
public static void main(String[] args) throws MessagingException, GeneralSecurityException {
Properties props = new Properties();

// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.qq.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
//开启了 SSL 加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);

Session session = Session.getInstance(props);

Message msg = new MimeMessage(session);
msg.setSubject("seenews 错误");
StringBuilder builder = new StringBuilder();
builder.append("url = " + "http://blog.csdn.net/never_cxb/article/details/50524571");
builder.append("\n页面爬虫错误");
builder.append("\n时间 " + new Date());
msg.setText(builder.toString());
msg.setFrom(new InternetAddress(" 发送人的邮箱地址"));//**发送人的邮箱地址**

Transport transport = session.getTransport();
transport.connect( "smtp.qq.com" , "发送人的邮箱地址" , "你的邮箱授权码" );
List<String> list=new ArrayList<>();
//实现群发,下面的方法也是可以实现群发,但是不太理想
transport.sendMessage(msg, InternetAddress.parse("3306907224@qq.com,269056581@qq.com"));
/*transport.sendMessage(msg, new Address[] {
new InternetAddress("3306907224@qq.com"),
new InternetAddress("269056581@qq.com"),
new InternetAddress("zhengmm@gz2000.net")
}
);*/
transport.close();
}
}

参看文章:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Mervin_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值