代码
public class SendMessageUtils {
public static final String MY_EMAIL_ACCOUNT = "你的邮箱地址@163.com";
public static final String MY_EMAIL_PASSWORD = "你设置的授权码(不是你的邮箱密码)";
public static final String MEAIL_163_SMTP_HOST = "smtp.163.com";
public static final String SMTP_163_PORT = "25";
public static final String RECEIVE_EMAIL_ACCOUNT = "***@**.com";
public static void main(String[] args) throws AddressException, MessagingException {
Properties p = new Properties();
p.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
p.setProperty("mail.smtp.port", SMTP_163_PORT);
p.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
p.setProperty("mail.smtp.auth", "true");
p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");
Session session = Session.getInstance(p, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
}
});
session.setDebug(true);
System.out.println("创建邮件");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
message.setRecipients(Message.RecipientType.TO, RECEIVE_EMAIL_ACCOUNT);
message.setSubject("文件");
message.setContent("<h1>美丽的菇凉</h1>", "text/html;charset=UTF-8");
message.setSentDate(new Date());
message.saveChanges();
System.out.println("准备发送");
Transport.send(message);
}
}
需要引用的jar包
<dependency >
<groupId >com.sun.mail </groupId >
<artifactId >javax.mail </artifactId >
<version >1.5.4 </version >
</dependency >
打开你的邮箱进行设置授权码
