java发邮件

public void sendEmail(){

String host = "smtp.163.com";             //smtp

  String from = "[email protected]";       //发送者

  String uname = "[email protected]";       //用户名

  String pword = "********";                 //密码

  

  Properties props = new Properties();

  props.put("mail.smtp.host", host);     //设置smtp主机

  props.put("mail.smtp.auth","true");     //使用smtp身份验证

  Session session = Session.getDefaultInstance(props, null);

 

  MimeMessage message = new MimeMessage(session);

  message.setFrom(new InternetAddress(from));       //设置发件人地址     

  message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //设置收件人地址

  message.setSubject("hot35最新密码");         //设置邮件标题

  message.setText("亲爱的商美客户,您好:\n商美系统为您提供的新密码为"+pwd+"。\n为保证您的帐号安全,建议在收到新密码后重置密码,防止帐号失窃.");         //设置邮件内容

        message.saveChanges();                          //保存所有

 

  //发送邮件

  Transport transport = session.getTransport("smtp");

  log.info("正在连接"+host);

  transport.connect(host, uname,pword);

  log.info("正在发送给"+to);

  transport.sendMessage(message, message.getAllRecipients());

  log.info("邮件发送成功");

}



注: 在工程下的lib目录中添加activation.jar包和mail.jar包

你可能感兴趣的:(java)