在jdk8以上需要包含2个jar包
- javamail: http://java.sun.com/products/javamail/downloads/index.html ,其中包括mail.jar和文档
- Activation.jar : http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#jaf-1.1.1-fcs-oth-JPR ,其中包括Activation.jar
- 然后在调用发送邮件的工具类 具体代码如下
package com.xmg.store.utils;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
//设置发送的协议
//props.setProperty("mail.transport.protocol", "SMTP");
//设置发送邮件的服务器
props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//设置发送人的帐号和密码 你的密码
return new PasswordAuthentication("simplyou@163.com", "xxxx");
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
//设置发送者
message.setFrom(new InternetAddress("simplyou@163.com"));
//设置发送方式与接收者
message.setRecipient(RecipientType.TO, new InternetAddress(email));
//设置邮件主题
message.setSubject("这是来自遥远的东方的一封邮件");
//设置邮件内容
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
public static void main(String[] args) throws AddressException, MessagingException {
MailUtils.sendMail("997745354@qq.com", "邮件内容");
}
}
- 如果不添加Activation.jar会报这个错误
java.lang.NoClassDefFoundError: javax/activation/DataSource
- 输入发送者的邮箱和密码 权限验证一定要打开 如果不打开会报
com.sun.mail.smtp.SMTPSendFailedException: 553 authentication is required,163 smtp1,C9GowABHeFeyYeFb
简书关注coderYJ
微博关注coderYJ
微信公众号关注coderYJ
网友评论