用Java 实现发送邮件功能

记录一下最近实现的 用Java 发送邮件的功能,我是用QQ邮箱

1.首先需要 两个jar 包

 

public class MailTest3 {

    public static void main(String[] args) {
         // 收件人电子邮箱
          String to = "11111@qq.com";
     
          // 发件人电子邮箱
          String from = "22222@qq.com";
     
          // 指定发送邮件的主机为 smtp.qq.com
          String host = "smtp.qq.com";  //QQ 邮件服务器
     
          // 获取系统属性
          Properties properties = System.getProperties();
     
          // 设置邮件服务器
          properties.setProperty("mail.smtp.host", host);//服务器地址
          properties.put("mail.smtp.port", "465"); // 服务器端口
     
          properties.put("mail.smtp.auth", "true");//是否要身份验证
          properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
          properties.put("mail.smtp.socketFactory.port", "465");
          properties.put("mail.smtp.starttls.enable", "true");
          properties.put("mail.smtp.socketFactory.fallback", "false"); 
          properties.put("mail.smtp.ssl.trust", "smtp.qq.com");
          // 获取默认session对象
          Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
             return new PasswordAuthentication("22222@qq.com", "kfsszldekrusdjie"); //发件人邮件用户名、密码(是从QQ邮箱获取到的授权码)
            }
           });
          
          session.setDebug(true);
     
          try{
             // 创建默认的 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("This is the Subject Line!");
     
             // 设置消息体
             message.setText("This is actual message");
     
             // 发送消息
             Transport.send(message);
             System.out.println("Sent message successfully");
          }catch (MessagingException mex) {
             mex.printStackTrace();
          }
    }

3.要开启SMTP 服务

 

 

 4.运行程序,可以收到邮件了 ^_^

 

* 之前用jdk1.7,一直出错,后来换成 1.8 的了就可以了,也不清楚具体声明原因。

 

转载于:https://www.cnblogs.com/shenyuxin/p/6847336.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值