简介
邮件使用在项目中备受青睐,很多网站用电子邮件来注册账户通知,邮箱找回账户,异常日志推送管理,以及系统业务消息推送等。系统为了模拟人为操作流程来发送邮件,我们接下来通过 Java 代码来创建电子邮件,并连接邮件服务器发送我们需要的邮件。
一、 Pom.xml中导入项目需要的mail包:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
二、详细代码:
package com.*.utils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
/**
* 邮件工具类
*/
public class MailUtils {
private static final String HOST = "smtp.yeah.net";//服务器地址{有些支持不同的服务主机地址不同端口也不同此处端口本为25因为被屏蔽所以用465}
private static final Integer PORT = 465;
private static final String USERNAME = "123123@yeah.net";
private static final String PASSWORD = "123123";
private static final String emailForm = "123123@yeah.net";
private static final String timeout = "80000";
private static final String personal = "邮件发送方名称";
private static JavaMailSenderImpl mailSender = createMailSender();
/**
* 邮件发送器
*
* @return 配置好的工具
*/
private static JavaMailSenderImpl createMailSender() {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost(HOST);
sender.setPort(PORT);
sender.setUsername(USERNAME);
sender.setPassword(PASSWORD);
sender.setDefaultEncoding("Utf-8");
Properties p = new Properties();
p.setProperty("mail.smtp.timeout", timeout);
p.setProperty("mail.smtp.auth", "true");
p.setProperty("mail.smtp.ssl.enable", "true");
p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
sender.setJavaMailProperties(p);
return sender;
}
/**
* 发送邮件
*
* @param to 接受人
* @param subject 主题
* @param html 发送内容
* @throws UnsupportedEncodingException 异常
*/
public static void sendMail(String to, String subject, String html) throws UnsupportedEncodingException, MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
// 设置utf-8或GBK编码,否则邮件会有乱码
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setFrom(emailForm, personal);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(html, true);
mailSender.send(mimeMessage);
}
public static void main (String[] args) throws UnsupportedEncodingException, MessagingException {
MailUtils m = new MailUtils();
m.sendMail("123123@qq.com","邮件主题","邮件内容");
}
}