首页 > 技术文章 > Java发送邮件的方法

joyce-cui 2017-08-26 15:01 原文

1.需要的jar

2.具体实现方法

 

 

 

1.设置邮箱主机、需要认证、邮箱协议

 

Properties pro=new Properties();

 

pro.setProperty("mail.host", "smtp.qq.com");

 

pro.setProperty("mail.smtp.auth", "true");

 

pro.setProperty("mail.transport.protocol", "smtp");

 

2.设置校验器

 

Authenticator auth=new Authenticator() {

 

@Override

 

protected PasswordAuthentication getPasswordAuthentication() {

 

return  new PasswordAuthentication("1375219202@qq.com","qzeagwfnyxvgjgff");

 

}

 

};

 

3.设置套接层,是为了保证协议以及运输的安全可靠性

 

MailSSLSocketFactory sf=new MailSSLSocketFactory();

 

sf.setTrustAllHosts(true);

 

pro.put("mail.smtp.ssl.enable", "true");

 

pro.put("mail.smto.ssl.SocketFactory", sf);

 

4.创建一封新邮件

 

 

 

//创建session

 

Session session=Session.getInstance(pro,auth);

 

session.setDebug(true);

 

//创建一份邮件

 

MimeMessage mime=new MimeMessage(session);

 

//填写发送人

 

mime.setFrom(new InternetAddress("18597842600@163.com"));

 

//填写接收人

 

mime.setRecipients(RecipientType.TO,"554735957@qq.com");

 

//设置主题

 

mime.setSubject("hello");

 

//设置正文

 

mime.setContent("hello,你好!","text/html;charset=utf-8");

 

Transport.send(mime);

 

System.out.println("发送成功");

 

Java发送带附件邮件的方法

 

只需要在设置正文那里注释掉,然后改成:

 

//发送带附件的邮件

 

MimeMultipart list =new MimeMultipart();

 

//创建body主体放置内容

 

MimeBodyPart b1=new MimeBodyPart();

 

b1.attachFile(new File("C:\\Users\\Administrator\\Desktop\\7.jpg"));

 

//中文转码

 

b1.setFileName(MimeUtility.encodeText("蜡笔小新耍流氓.jpg"));

 

list.addBodyPart(b1);

 

MimeBodyPart b2=new MimeBodyPart();

 

b2.setContent("hello,你好!","text/html;charset=utf-8");

 

list.addBodyPart(b2);

 

mime.setContent(list);

 

Transport.send(mime);

 

System.out.println("发送成功");

 

推荐阅读