java原生API邮件发送
在发送邮件前先确定自己邮箱类型,邮箱服务器地址,第三方管理是否开启,等等
package test.util;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class SendEmail{
public static void sendEmail(String to,String content)throws MessagingExceptioon{
//1创建连接对象
Properties pro=new Properties();
//2.设置协议
pro.put("mail.transport.protocol","smtp");
//3.设置发送邮件服务器
pro.put("mail.smtp.host","smtp.office365.com");
//4.进行授权
pro.put("mail.smtp.auth","true");
//5.邮件服务器具体端口及协议设定
pro.setProperties("mail.smtp.port","587");
pro.setProperties("mail.smtp.socketFactory.port","587");
pro.setProperties("mail.smtp.starttls.enable","true");
//6.认证信息
Session s=Session.getInstance(pro,new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("你的邮箱","你的密码");
}
}
);
//7.创建邮件对象
Message m=new MimeMessage(s);
//8.设置邮件发送人
m.setFrom(new InternetAddress("你的邮箱"));
//9.设置接收人,to为接收者邮箱
m.setRecipient(RecipientType.TO,new InternetAddress("to"));
//10.设置主题
m.setSubject("xxxx");
//11.设置内容,content为内容
m.setContent(content,"text/html;charset=utf-8");
//12.发送
Transport.send(m);
}
}