首先要在maven添加javamail支持
javax.activation activation 1.1 不加的话会报javax.mail.MessagingException异常 javax.mail 1.4
代码如下 : 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 //获取用于发送邮件的Session18 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 @Override32 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异常 具体如何设置可自行百度。