JavaMail使用Hotmail的SMTP

最近在研究如何用JavaMail来发邮件,其中碰到一个问题就是美国的远程机无法连接126邮箱的SMTP,因为万恶的GFW。于是开始寻找国外邮箱的SMTP,最终发现了Hotmail的使用方法,代码如下



try {
String sender="metricsdart@hotmail.com"; //hotmail 邮箱
String recipient="regression126@126.com"; //收件人
String subject="Metrics Result"; //邮件标题
String password="************"; //密码。。。


//Set the properties for Mailbox
Properties properties=new Properties();
properties.put("mail.smtp.auth", "true"); //邮箱需要验证设置为True
properties.put("mail.smtp.starttls.enable", "true"); //hotmail 需要起tls
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "smtp.live.com");
properties.put("mail.smtp.port", "587"); //tls的端口为587
Session session=Session.getInstance(properties);

//Set the message for Email
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender));
msg.setRecipient(Message.RecipientType.TO,new InternetAddress(recipient));
msg.setSentDate(new Date());
msg.setSubject(subject);

//If no attachment, no need to use Multipart
MimeMultipart multipart=new MimeMultipart();
for(int i=0;i<filepath.length;i++){
File file=new File(filepath[i]);
BodyPart attachPart=new MimeBodyPart();
DataSource dataSource=new FileDataSource(file);
attachPart.setDataHandler(new DataHandler(dataSource));
attachPart.setFileName(file.getName());
multipart.addBodyPart(attachPart);
}
msg.setContent(multipart);



Transport tran = session.getTransport("smtp");
System.out.println("Before connect");
tran.connect("smtp.live.com", sender, password);
System.out.println("connect successfully");
tran.sendMessage(msg, msg.getAllRecipients());
System.out.println("邮件发送成功");

} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值