package com.cxf.util;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMessage.RecipientType;import java.util.Properties;/*** 发送邮件工具类*/public final class MailUtil {private MailUtil() {}/*** 发送邮件* 参数一:发送邮件给谁* 参数二:发送邮件的内容*/public static void sendMail(String toEmail, String emailMsg) {//1_创建Java程序与163邮件服务器的连接对象Properties props = new Properties();props.put("mail.smtp.host", "");props.put("mail.smtp.auth", "true");//创建第三方邮箱登录时的认证对象Authenticator auth = new Authenticator() {public PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("zhang*******@", "RQH********");}};Session session = Session.getInstance(props, auth);//2_创建一封邮件Message message = new MimeMessage(session);try {//设置邮箱发送到地址message.setFrom(new InternetAddress("zhang******@"));//设置接收信息的邮箱地址message.setRecipient(RecipientType.TO, new InternetAddress(toEmail));//设置邮箱的主题message.setSubject("邮箱主题");//设置邮箱的正文message.setContent(emailMsg, "text/html;charset=UTF-8");//3_发送邮件Transport.send(message);} catch (MessagingException e) {throw new RuntimeException("邮件发送失败");}}}
相应的jar包
<dependency><groupId>javax.mail</groupId><artifactId>javax.mail-api</artifactId><version>1.5.6</version></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.5.3</version></dependency>