您的位置:首页 > 编程语言 > Java开发

JAVAMail 实现 QQ邮件发送

2017-03-31 15:45 363 查看
代码参考了http://www.runoob.com/java/java-sending-email.html 的教程
成功测试
package test;import java.security.GeneralSecurityException;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;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 Test_Mail {public static void main(String [] args){// 收件人电子邮箱String to = "****@qq.com";// 发件人电子邮箱String from = "*****@qq.com";// 指定发送邮件的主机为 smtp.qq.comString host = "smtp.qq.com";  //QQ 邮件服务器// 获取系统属性Properties properties = System.getProperties();// 设置邮件服务器properties.setProperty("mail.smtp.host", host);properties.put("mail.smtp.auth", "true");try{// 以下四行代码 对于QQ邮箱的邮件发送是必须的MailSSLSocketFactory ssl = new MailSSLSocketFactory();ssl.setTrustAllHosts(true);properties.put("mail.smtp.ssl.enable", "true");properties.put("mail.smtp.ssl.socketFactory", ssl);// 获取默认session对象Session session = Session.getDefaultInstance(properties,new Authenticator(){public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication("844280830@qq.com", "gbxxtbrxylwfbebc"); //发件人邮件用户名、密码}});// 创建默认的 MimeMessage 对象MimeMessage message = new MimeMessage(session);// Set From: 头部头字段message.setFrom(new InternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set Subject: 头部头字段message.setSubject("邮件的主题");// 设置消息体message.setText("邮件内容");// 发送消息Transport.send(message);System.out.println("发送成功");}catch (MessagingException mex) {mex.printStackTrace();} catch (GeneralSecurityException e) {e.printStackTrace();}}}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  邮件 JAVAMail