运用java代码实现发邮件

本文介绍如何通过163邮箱配置SMTP服务,实现利用Java程序发送密码重置邮件的功能。文中详细展示了配置过程及代码实现。
 方法:(我的是163邮箱

登陆自己的邮箱 开启POP3服务 和 SMTP服务  (为了有使用权限 , 用Foxmail等客户端登录也要设置)


获取授权码,用于代码中    

 props.setProperty("mail.sender.auth", "xxxxxxxxxxxxxx");






 public static void sendResetPswMail(String emailTo, String userName, String newPsw)throws MessagingException, GeneralSecurityException{
    	Properties props = new Properties();

//      // 开启debug调试
//      props.setProperty("mail.debug", "true");
      // 发送服务器需要身份验证
      props.setProperty("mail.smtp.auth", "true");
      // 设置邮件服务器主机名
      props.setProperty("mail.host", "smtp.163.com");
      // 发送邮件协议名称
      props.setProperty("mail.transport.protocol", "smtp");        
      props.setProperty("mail.sender.user", "xxxxxxxx@163.com"); // 这里是你发送邮件的的邮箱
      props.setProperty("mail.sender.auth", "xxxxxxxxxxxxxx");// 授权密码


      MailSSLSocketFactory sf = new MailSSLSocketFactory();
      sf.setTrustAllHosts(true);
      props.put("mail.smtp.ssl.enable", "true");
      props.put("mail.smtp.ssl.socketFactory", sf);


      Session session = Session.getInstance(props);

    // 发送内容
      Message msg = new MimeMessage(session);
      msg.setSubject("密码重置");      
      
      String contend = userName + ", 您好!\n您的新密码为:" + newPsw + "\n新密码由系统随机生成,您可以登录后修改为其它密码.\n\n  www.amz16888.com"; 
              
      msg.setText(contend);
      msg.setFrom(new InternetAddress(props.getProperty("mail.sender.user")));


      Transport transport = session.getTransport();
      transport.connect(props.getProperty("mail.host"), props.getProperty("mail.sender.user"), props.getProperty("mail.sender.auth"));//这里是发送人的账号 后面是授权码

      transport.sendMessage(msg, new Address[] { new InternetAddress(emailTo) }); //这里是接收人的账号
      transport.close();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lying~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值