使用java实现发送邮件的功能


首先要在maven添加javamail支持


<dependency>
 <groupId>javax.activation</groupId>
 <artifactId>activation</artifactId>
 <version>1.1</version>
</dependency>
<dependency>
 <groupId>javax.mail</groupId>
 <artifactId>mail</artifactId>
 <version>1.4</version>
</dependency>
不加的话会报javax.mail.MessagingException异常
代码如下  :

1
package com.learn.util; 2 3 /** 4 * Created by Wangqingyu on 2017/6/3. 5 */ 6 7 import javax.mail.*; 8 import javax.mail.internet.AddressException; 9 import javax.mail.internet.InternetAddress; 10 import javax.mail.internet.MimeMessage; 11 import java.util.Date; 12 import java.util.Properties; 13 14 15 public class SendEmailUtil { 16 17 //获取用于发送邮件的Session 18 public static Session getSession() throws MessagingException { 19 //创建连接对象 连接到邮件服务器 20 Properties props = new Properties(); 21 22 //设置发送邮件的基本参数 23 //发送邮件服务器 24 props.put("mail.smtp.host", "smtp.163.com"); 25 props.put("mail.store.protocol" , "smtp");//设置协议 26 //发送端口 27 props.put("mail.smtp.port", "25"); 28 props.put("mail.smtp.auth", "true"); 29 30 Authenticator authenticator = new Authenticator() { 31 @Override 32 protected PasswordAuthentication getPasswordAuthentication() { 33 return new PasswordAuthentication("邮件发自的邮箱@163.com","邮件发自的邮箱授权码"); 34 } 35 }; 36 Session session = Session.getDefaultInstance(props, authenticator); 37 return session; 38 } 39 40 //发送邮件,String email为邮件的目标邮箱 41 public static void send(String email, String sb) throws MessagingException{ 42 Session session = getSession(); 43 44 try { 45 Message msg = new MimeMessage(session); 46 //设置message属性 47 msg.setFrom(new InternetAddress("邮件发自的邮箱@163.com")); 48 //InternetAddress[] addrs = {new InternetAddress(email)}; 49 msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); 50 msg.setSubject("贵宾xxx先生");//邮箱标题 51 msg.setSentDate(new Date());//邮箱时间 52 msg.setContent(sb, "text/html;charset=utf-8");//邮箱内容和格式 53 //必须为text/html;格式,纯文本格式会被当做垃圾邮件 54 55 //开始发送 56 Transport.send(msg); 57 } catch (AddressException e) { 58 e.printStackTrace(); 59 } catch (MessagingException e) { 60 e.printStackTrace(); 61 } 62 63 } 64 } 65
注意的点:上文中提到的邮箱授权码而不是密码,是因为邮件的发自邮箱需要设置POP3/SMTP/IMAP服务,否则会报503异常
具体如何设置可自行百度。





原文地址:https://www.cnblogs.com/RunningSir/p/6952623.html