package star.july.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message.RecipientType;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
//JavaMail发送邮件
public class JavaMail {
public static void main(String[] args) throws Exception, Exception {
//1、创建链接并登录服务器
/**
* 参数一:连接服务器的主机地址和登陆配置
* 参数二:指定用户名和密码(需要验证登陆的(加密的))
*/
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.sina.com");//邮箱服务器,端口默认25
prop.setProperty("mail.smtp.auth", "true"); //是否需要验证登录
//创建一个Authenticator的子类对象
Authenticator auth = new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("ericxu12345@sina.com", "eric12345");
}
};//Authenticator:用于对用户名和密码进行加密
Session session = Session.getDefaultInstance(prop,auth);
//打开发送的debug模式:看到发送邮件的全过程
session.setDebug(true);
System.out.println(session);
//2、创建一封邮件(指定发件人,收件人,主题,内容)
MimeMessage mail = new MimeMessage(session);
//2.1、指定发件人(和登陆用户一致)
mail.setFrom(new InternetAddress("ericxu12345@sina.com"));
//2.2 指定收件人
//参数一:收件类型 TO:收件人 CC:抄送人 BCC:密抄送人
mail.setRecipient(RecipientType.TO,
new InternetAddress("jackyun12345@sina.com"));
//2.3 主题
mail.setSubject("这是一封javamail发送的测试邮件");
//2.4 内容
mail.setContent("测试内容:七夕快乐!",
"text/plain;charset=utf-8");
//3 发送邮件
Transport.send(mail);
}
}
JavaMail邮件的发送
最新推荐文章于 2023-07-08 23:55:47 发布