版权声明:本文为博主原创文章,如果转载请务必注明出自本博客:qq_2300688967,否则追究责任。 https://blog.csdn.net/qq_2300688967/article/details/83089542
1,导入maven依赖:
<!-- https://mvnrepository.com/artifact/javax.mail/mail --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.5.0-b01</version> </dependency>
2,java代码示例:
import java.util.Date;
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;
public class SendEmail {
/** 发件人 账号和密码**/
public static final String MY_EMAIL_ACCOUNT = "[email protected]";
// 密码,是你自己的设置的授权码,
// 获取方式:登陆网页邮箱,设置-》客户端授权密码
public static final String MY_EMAIL_PASSWORD = "xxx";
// SMTP服务器(这里用的163 SMTP服务器)
public static final String MEAIL_163_SMTP_HOST = "smtp.163.com";
/** 端口号,这个是163使用到的;QQ的应该是465或者875 **/
public static final String SMTP_163_PORT = "25";
/** 收件人 **/
public static final String RECEIVE_EMAIL_ACCOUNT = "[email protected]";
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);
}
}