一、首先打开QQ邮箱的SMTP服务,由于QQ邮箱对于通常的用户都是默认关闭SMTP服务的。html
找到SMTP服务的选项,能够看到此处默认是关闭的,点击开启,而后腾讯会进行一些身份验证,身份验证经过之后,腾讯会给出一个用于使用SMTP的16位口令,此处这个口令必定牢记,由于后面要使用SMTP功能必需要用到这个口令,没有这个口令即便知道QQ邮箱密码也没有用,此处未给出口令的截图,毕竟为了隐私保密,否则你们均可以登陆使用个人QQ邮箱SMTP服务了。后面咱们将该口令记为SMTP口令。 java
生成受权码。服务器
首先,要使用Java的邮箱功能须要javax.mail这个jar包:测试
依赖:spa
<!-- email start --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <!-- email end -->
发送邮件代码:.net
// 建立Properties 类用于记录邮箱的一些属性 Properties props = new Properties(); // 表示SMTP发送邮件,必须进行身份验证 props.put("mail.smtp.auth", "true"); //此处填写SMTP服务器 props.put("mail.smtp.host", "smtp.qq.com"); //端口号,QQ邮箱给出了两个端口,可是另外一个我一直使用不了,因此就给出这一个587 props.put("mail.smtp.port", "587"); // 此处填写你的帐号 props.put("mail.user", "xxxxxxx@qq.com"); // 此处的密码就是前面说的16位STMP口令 props.put("mail.password", "xxxxxxxxxxxxxxxxxxx"); // 构建受权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // 用户名、密码 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用环境属性和受权信息,建立邮件会话 Session mailSession = Session.getInstance(props, authenticator); // 建立邮件消息 MimeMessage message = new MimeMessage(mailSession); // 设置发件人 InternetAddress form = new InternetAddress( props.getProperty("mail.user")); message.setFrom(form); // 设置收件人的邮箱 InternetAddress to = new InternetAddress("xxxxxxxx@qq.com"); message.setRecipient(RecipientType.TO, to); // 设置邮件标题 message.setSubject("测试邮件"); // 设置邮件的内容体 message.setContent("这是一封测试邮件", "text/html;charset=UTF-8"); // 最后固然就是发送邮件啦 Transport.send(message);
好了,以上就能够了。code
若是生产环境不能发送邮件,则要绑定host。orm