1.开启邮件服务
如果选用QQ邮箱作为代理服务的话,需要进行一些设置:
登录邮箱后,点击设置->账户
将四个服务开启,然后点击生成授权码,获取到授权码以便使用。
2.邮件发送
通过java的mail工具包,发送邮件,话不多说,上代码。
package ext.plm.mail; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; public class EmailTestSend { public void send(String subject,String content) throws Exception{ // 创建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", "发件人邮箱"); // 此处填写16位STMP授权码 props.put("mail.password", "生成的授权码"); // 构建授权信息,用于进行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("收件人邮箱"); message.setRecipient(RecipientType.TO, to); // 设置邮件标题 message.setSubject(subject); // 设置邮件的内容体 message.setContent(content, "text/html;charset=UTF-8"); // 最后当然就是发送邮件啦 Transport.send(message); } }