javaMail发送邮件
jar包:
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.4</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
工具类
package com.ufclub.util.mail; import com.ufclub.DTO.mail.FoxmailPropertiesDTO; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * 发送邮件 * * @author zhoushixia * @date 2017-08-10 */ public class SendMailUtil { private static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class); private static boolean isInit = false; private static Properties prop; public static void setProperty(FoxmailPropertiesDTO foxmailPropertiesDTO){ if(!isInit){ logger.info("{0}邮箱初始化开始,发送者为{1},接受者为{2}",foxmailPropertiesDTO.getMailCode(),foxmailPropertiesDTO.getSenderAddress(),foxmailPropertiesDTO.getReceiveAddress()); prop = new Properties(); prop.setProperty("mail.host",foxmailPropertiesDTO.getMailHost()); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); isInit = true; logger.info("{0}邮箱初始化成功,发送者为{1},接受者为{2}",foxmailPropertiesDTO.getMailCode(),foxmailPropertiesDTO.getSenderAddress(),foxmailPropertiesDTO.getReceiveAddress()); } } public static void sendMail(FoxmailPropertiesDTO foxmailPropertiesDTO){ if(StringUtils.isBlank(foxmailPropertiesDTO.getReceiveAddress())){ logger.info("{0}发送邮件,邮件无接收者",foxmailPropertiesDTO.getMailCode()); return; } try{ setProperty(foxmailPropertiesDTO); //创建session Session session = Session.getInstance(prop); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //通过session得到transport对象 Transport ts = session.getTransport(); //使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 ts.connect(foxmailPropertiesDTO.getMailHost(), foxmailPropertiesDTO.getSenderAddress(), foxmailPropertiesDTO.getSenderPassword()); //创建邮件 Message message = createSimpleMail(session,foxmailPropertiesDTO); //发送邮件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); }catch (Exception e) { logger.error("发送邮件异常"); e.printStackTrace(); } } public static MimeMessage createSimpleMail(Session session,FoxmailPropertiesDTO foxmailPropertiesDTO) throws Exception { //创建邮件对象 MimeMessage message = new MimeMessage(session); //指明邮件的发件人 message.setFrom(new InternetAddress(foxmailPropertiesDTO.getSenderAddress())); InternetAddress[] internetAddressTo = new InternetAddress().parse(foxmailPropertiesDTO.getReceiveAddress()); message.addRecipients(Message.RecipientType.TO, internetAddressTo); //邮件的文本内容 message.setContent(foxmailPropertiesDTO.getSendContent(), "text/html;charset=UTF-8"); //返回创建好的邮件对象 return message; } }
数据库截图
调用截图