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 MailboxProperties properties=new Properties();properties.put("mail.smtp.auth", "true"); //邮箱需要验证设置为Trueproperties.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 blocke.printStackTrace(); } }