小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java 发送邮件

发布者: 小白教程



用户认证部分

如果需要提供用户名和密码给e-mail服务器来达到用户认证的目的,你可以通过如下设置来完成:

  1. props.put("mail.smtp.auth", "true");
  2. props.setProperty("mail.user", "myuser");
  3. props.setProperty("mail.password", "mypwd");

e-mail其他的发送机制和上述保持一致。

需要用户名密码验证邮件发送实例:

本实例以QQ邮件服务器为例,你需要在登录QQ邮箱后台在"设置"=》账号中开启POP3/SMTP服务 ,如下图所示:

qqmailset

Java 代码如下:

  1. // 需要用户名密码邮件发送实例
  2. //文件名 SendEmail2.java
  3. //本实例以QQ邮箱为例,你需要在qq后台设置
  4. import java.util.Properties;
  5. import javax.mail.Authenticator;
  6. import javax.mail.Message;
  7. import javax.mail.MessagingException;
  8. import javax.mail.PasswordAuthentication;
  9. import javax.mail.Session;
  10. import javax.mail.Transport;
  11. import javax.mail.internet.InternetAddress;
  12. import javax.mail.internet.MimeMessage;
  13. public class SendEmail2
  14. {
  15. public static void main(String [] args)
  16. {
  17. // 收件人电子邮箱
  18. String to = "xxx@qq.com";
  19. // 发件人电子邮箱
  20. String from = "xxx@qq.com";
  21. // 指定发送邮件的主机为 localhost
  22. String host = "smtp.qq.com"; //QQ 邮件服务器
  23. // 获取系统属性
  24. Properties properties = System.getProperties();
  25. // 设置邮件服务器
  26. properties.setProperty("mail.smtp.host", host);
  27. properties.put("mail.smtp.auth", "true");
  28. // 获取默认session对象
  29. Session session = Session.getDefaultInstance(properties,new Authenticator(){
  30. public PasswordAuthentication getPasswordAuthentication()
  31. {
  32. return new PasswordAuthentication("xxx@qq.com", "qq邮箱密码"); //发件人邮件用户名、密码
  33. }
  34. });
  35. try{
  36. // 创建默认的 MimeMessage 对象
  37. MimeMessage message = new MimeMessage(session);
  38. // Set From: 头部头字段
  39. message.setFrom(new InternetAddress(from));
  40. // Set To: 头部头字段
  41. message.addRecipient(Message.RecipientType.TO,
  42. new InternetAddress(to));
  43. // Set Subject: 头部头字段
  44. message.setSubject("This is the Subject Line!");
  45. // 设置消息体
  46. message.setText("This is actual message");
  47. // 发送消息
  48. Transport.send(message);
  49. System.out.println("Sent message successfully....from ");
  50. }catch (MessagingException mex) {
  51. mex.printStackTrace();
  52. }
  53. }
  54. }
123
上一篇:Java 网络编程下一篇:Java 多线程编程

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:16 , Processed in 0.018197 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部