最近自己折腾了下Java中利用mai发送QQ邮件
1.QQ邮箱设置
1.1 进去QQ邮箱-->设置-->账号-->进行设置如下图
2.foxmail设置(由于我要利用它收邮件)
2.1 参照官方的设置即可 http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371
ps:填写的邮箱密码是独立密码:需要注意的就是SSL链接要勾选;smtp端口是465
3.Java中代码配置
3.1 发送邮件配置代码
//发送邮箱验证 try { Properties prop = new Properties(); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.host", "smtp.qq.com"); prop.setProperty("mail.smtp.auth", "true"); prop.put("mail.smtp.port","25"); prop.setProperty("mail.debug", "true"); Authenticator authenticator = new PopAuthenticator("1274444444@qq.com", "4444444"); //创建会话 Session session = Session.getInstance(prop,authenticator); //填写信封写信 Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("1271099894@qq.com")); msg.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); msg.setSubject(user.getUsername()+"激活邮箱!"); msg.setText(user.getUsername()+",你好请到这个地址激活你的账号:http://www.estore.com/ActiveServlet?activecode="+user.getActivecode()); //验证用户名密码发送邮件 Transport transport = session.getTransport(); //transport.connect("1274444444@qq.com","4444444"); transport.send(msg); }
3.2辅助类
public class PopAuthenticator extends Authenticator { String userName = null; String password = null; public PopAuthenticator() { } public PopAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }
3.3 如果要发送html可以参考如下代码:
MimeMessage mailMessage = new MimeMessage(sendMailSession); mailMessage.setFrom(new InternetAddress("1219999@qq.com")); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); mailMessage.setSubject(subject, "UTF-8"); mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); html.setContent(content.trim(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); mailMessage.setContent(mainPart); Transport.send(mailMessage);