大多数邮箱发送有office或者注册验证码,特别是在玩网络的这块,很多网站都有邮箱注册的验证码,小编偷偷跟你们说,是因为邮箱免费的,手机验证码需要收费的,哈哈。。。
如果对邮件收发过程完全不了解的话,可以花三分钟的时间到慕课网了解一下,讲得算是非常清楚了,这里就不赘述了。放张图回忆一下:
邮箱准备
Maven配置
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
代码
package currency.util;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SingleMailSend {
private static String email = "aaaaa@qq.com";// 收件人邮箱
private static String code;// 激活码
public static void run() {
// 1.创建连接对象javax.mail.Session
// 2.创建邮件对象 javax.mail.Message
// 3.发送一封激活邮件
String from = "bbbb@qq.com";// 发件人电子邮箱
String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
Properties properties = System.getProperties();// 获取系统属性
properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
properties.setProperty("mail.smtp.auth", "true");// 打开认证
try {
//QQ邮箱需要下面这段代码,163邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
// 1.获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("bbbb@qq.com", "xxxxxx"); // 发件人邮箱账号、授权码
}
});
// 2.创建邮件对象
Message message = new MimeMessage(session);
// 2.1设置发件人
message.setFrom(new InternetAddress(from));
// 2.2设置接收人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 2.3设置邮件主题
message.setSubject("邮件主题");
// 2.4设置邮件内容
String content = "邮件内容";
message.setContent(content, "text/html;charset=UTF-8");
// 3.发送邮件
Transport.send(message);
System.out.println("邮件成功发送!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] arge) {
run();
}
}
希望这篇文章对您有帮助
文章评论