发送简单邮件

导包

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>

编写程序

package com.Google;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.imageio.spi.ImageInputStreamSpi;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class mailTest {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host","stmp.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发送邮箱的五个步骤
//1,创建整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮箱用户名,授权码(Authentication,验证)
return new PasswordAuthentication("2034281740@qq.com", "授权码");
}
});
session.setDebug(true);
//2,通过Session获取transport对象
Transport transport = session.getTransport();
//3,使用邮箱的用户名和授权码,连接邮箱服务器
transport.connect("smtp.qq.com","2034281740@qq.com", "授权码");
//4,编写内容
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("2034281740@qq.com"));//设置发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("2034281740@qq.com"));//设置收件人
message.setSubject("叫我靓仔");//设置邮件标题
message.setContent("叼毛,叼毛","text/html;charset=UTF-8");
//5,发送邮箱
transport.sendMessage(message, message.getAllRecipients());
}
}
posted @   小罗要有出息  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示