package com.test2;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
class SimpleAuthenticator extends Authenticator{
private String userName;
private String password;
public SimpleAuthenticator(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.userName, this.password);
}
}
package com.test2;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import com.sun.mail.smtp.SMTPMessage;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendMail {
public static void sendMail() throws UnsupportedEncodingException, GeneralSecurityException{
String userName = "发件人@qq.com";
String password="aaaafmlvyjrxbfig";//授权码
String subject = "邮件标题"; // 邮件标题
String body = "邮件内容"; // 邮件内容
Properties props=System.getProperties();
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.socketFactory.port", 465);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.ssl.socketFactory", sf);
props.put("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getDefaultInstance(props,new SimpleAuthenticator(userName, password) );
session.setDebug(true);
SMTPMessage message=new SMTPMessage(session);
try {
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人@qq.com"));//收件人
message.setSubject(subject);
message.setText(body);
String nickName="昵称";
nickName=javax.mail.internet.MimeUtility.encodeText(nickName);
/*设置发件人 发件人必须要和Authenticator验证的帐号一致*/
message.setFrom(new InternetAddress(nickName+" <发件人@qq.com>"));
Transport transport = session.getTransport("smtp");
transport.connect(userName, password);
Transport.send(message);
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
SendMail.sendMail();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.利用发件人邮箱发邮件,需要去发件邮箱设置->账户开启stmp服务
,开启服务之后,生成授权码
2.需要引入mail.jar