现在一般网站注册的时候,会填写邮箱,然后发送一个信息进你的邮箱,进行账号激活,这几天根据网上的资料学习,完成了简单的邮件发送功能,记录下来,以便后续的开发
第一步:
打开qq邮箱的smtp服务
1.进入qq邮箱–>点击设置–>点击账户
2.找到以下
3.点击后面的开启按钮,根据提示一步步操作,即可得到16位授权码
以下为代码部分:
package mail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
public class Sendmail {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
//打开调试模式
prop.setProperty("mail.debug", "true");
//此处为qq的邮箱服务器,有人说可以换成smtp.exmail.qq.com,但是没有成功
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
//因为qq邮箱发送邮件时,需要进行SSL加密,所以需要以下四行代码
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// prop.setProperty("mail.smtp.starttls.enable", "true");
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
ts.connect("smtp.qq.com", "qq号", "注意此处为授权码,而非qq密码");
//4、创建邮件
Message message = createSimpleMail(session);
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
public static MimeMessage createSimpleMail(Session session)
throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("*****@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("*****@qq.com"));
//邮件的标题
message.setSubject("只包含文本的简单邮件");
//邮件的文本内容
message.setContent("你好啊!", "text/html;charset=UTF-8");
//返回创建好的邮件对象
return message;
}
}
验证成功: