发送一个简单邮件
package com.heng;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Hengxianxianbei@qq.com", "授权码");
}
});
session.setDebug(true);
Transport ts = session.getTransport();
ts.connect("smtp.qq.com", "Hengxianxianbei@qq.com", "授权码");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("Hengxianxianbei@qq.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱"));
message.setSubject("hello");
message.setContent("<h1 style='color: red'>你好啊</h1>", "text/html;charset=UTF-8");
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}