javamail例子

public  boolean SendMail(TestBean testBean){
     int port   = 25;         //smtp端口
        String server  = "smtp.126.com";      //smtp服务器地址
        String from  = "发送者@126.com";  //发送者
        String user  = "发送者";     //发送者用户名
        String password = "***************";      //发送者密码
        try {
               Properties props = new Properties();
               //smtp参数设置
               props.put("mail.smtp.host", server);
               props.put("mail.smtp.port", String.valueOf(port));
               props.put("mail.smtp.auth", "true");  //smtp是否需要认证
               Transport transport = null;
               //创建Session
               Session session = Session.getDefaultInstance(props, null);
               //通过Session创建Transport
               transport = session.getTransport("smtp");
               transport.connect(server, user, password); //建立同服务器的连接
               //创建Message
               MimeMessage msg = new MimeMessage(session);
               msg.setSentDate(new Date());  //设置发送时间
               InternetAddress fromAddress = new InternetAddress(from);
               msg.setFrom(fromAddress);  //设置发送人地址
               InternetAddress[] toAddress = new InternetAddress[1];
               toAddress[0] = new InternetAddress("接收者@qq.com");
               msg.setRecipients(Message.RecipientType.TO, toAddress); //设置收件人地址
               msg.setSubject("email-测试", "UTF-8"); //设置主题信息
               msg.setText("发送邮件内容测试", "UTF-8"); //设置内容信息
               msg.saveChanges();
               //Transport完成向Recipients发送Message
               transport.sendMessage(msg, msg.getAllRecipients());
               transport.close();                       //关闭
        } catch (NoSuchProviderException e) {
               logger.error(e);
        } catch (MessagingException e) {
               logger.error(e);
        }
        return true;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值