Java发送邮件
准备工作
将mail.jar和activation.jar加入classpath.
说明
发送方为163邮箱,需要设置host等参数。
接收方可以是其他种类邮箱,比如qq邮箱等。
简单邮件发送
注意创建session时需要传入授权参数,否则会抛出异常 javax.mail.AuthenticationFailedException: failed to connect, no password specified?
1 public static void Send163Email() { 2 String to = "to@163.com"; 3 String from = "from@163.com"; 4 5 Properties properties = System.getProperties(); 6 7 properties.put("mail.host", "smtp.163.com"); 8 properties.put("mail.transport.protocol", "smtp"); 9 properties.put("mail.smtp.auth", true); 10 11 Session session = Session.getDefaultInstance(properties, 12 new javax.mail.Authenticator(){ 13 protected PasswordAuthentication getPasswordAuthentication() { 14 return new PasswordAuthentication( 15 "from@163.com", "授权码");// Specify the Username and the PassWord 16 } 17 }); 18 session.setDebug(true); 19 20 MimeMessage message = new MimeMessage(session); 21 22 try { 23 message.setFrom(new InternetAddress(from)); 24 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 25 message.setSubject("This is the Subject Line!"); 26 message.setText("This is actual message."); 27 Transport.send(message); 28 System.out.println("Sent message sucessfully!"); 29 } catch (MessagingException mex) { 30 mex.printStackTrace(); 31 } 32 }
带附件邮件发送
1 public static void Send163EmailWithAttachment() { 2 String to = "to@163.com"; 3 String from = "from@163.com"; 4 5 Properties properties = System.getProperties(); 6 7 properties.put("mail.host", "smtp.163.com"); 8 properties.put("mail.transport.protocol", "smtp"); 9 properties.put("mail.smtp.auth", true); 10 11 Session session = Session.getDefaultInstance(properties, 12 new javax.mail.Authenticator(){ 13 protected PasswordAuthentication getPasswordAuthentication() { 14 return new PasswordAuthentication( 15 "from@163.com", "授权码");// Specify the Username and the PassWord 16 } 17 }); 18 session.setDebug(true); 19 20 MimeMessage message = new MimeMessage(session); 21 22 try { 23 message.setFrom(new InternetAddress(from)); 24 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 25 message.setSubject("This is the Subject Line(Text and file)!"); 26 27 BodyPart messageBodyPart=new MimeBodyPart(); 28 messageBodyPart.setText("This is a message body.\n2017年11月28日"); 29 Multipart multipart=new MimeMultipart(); 30 multipart.addBodyPart(messageBodyPart); 31 //attachment 32 messageBodyPart=new MimeBodyPart(); 33 String filename="文件名(带路径)"; 34 DataSource source=new FileDataSource(filename); 35 messageBodyPart.setDataHandler(new DataHandler(source)); 36 messageBodyPart.setFileName(filename); 37 multipart.addBodyPart(messageBodyPart); 38 39 message.setContent(multipart); 40 Transport.send(message); 41 System.out.println("Sent message sucessfully!"); 42 } catch (MessagingException mex) { 43 mex.printStackTrace(); 44 } 45 }
『注:本文来自博客园“小溪的博客”,若非声明均为原创内容,请勿用于商业用途,转载请注明出处http://www.cnblogs.com/xiaoxi666/』