话不多说上代码:
1.需要依赖包:mail.jar
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>
2.mail工具类:
此类里面的一些邮箱服务器参数需要自己去配置修改,否则无法测试通过(如果写在了配置文件里,可以通过注解方式来获取等)。如果你不需要日志等打印,请注释掉日志代码。此类里面封装了连个发邮件的方法,参数是EmailInfo的只是对下面测试中的那个方法的一个封装,如果你需要封装,博客最下面会附上代码。如果不需要,请忽略;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public abstract class EmailUtil {
private final static Logger logger = LoggerFactory.getLogger(EmailUtil.class);
private static JavaMailSenderImpl mailSender;
private static String mailbox_server;
private EmailUtil() {
}
static{
init();
}
private static void init(){
mailSender = new JavaMailSenderImpl();
mailSender.setDefaultEncoding("UTF-8");
mailSender.setPort("mailbox_server_port"));//这里的参数都是从配置文件里读取的 自己修改 端口号是数值型
mailSender.setHost("mailbox_server_host");//主机地址
mailSender.setUsername("mailbox_server_username");//邮箱服务器发件人名称
mailSender.setPassword("mailbox_server_password");//邮箱服务器密码
mailbox_server ="mailbox_server";//这些对应填写就行,也不知道写的对应不对应
}
private static void validateEmail(String[] email) {
if(email == null)
throw new EmailUtilException("邮箱为null");
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
for (int i = 0; i < email.length; i++) {
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email[i]);
if(!matcher.matches())
throw new EmailUtilException("邮箱格式校验错误...");
}
}
public static void sendEmail(EmailInfo emailInfo){
if(null == emailInfo)
return;
validateEmail(emailInfo.getDestination());
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setFrom(mailbox_server);
helper.setSubject(emailInfo.getTitle());
helper.setText(emailInfo.getMailContent());
helper.setTo(emailInfo.getDestination());
mailSender.send(message);
} catch (Exception e) {
logger.warn("发送邮件失败..."+emailInfo.toString());
e.printStackTrace();
}
}
public static void sendEmail(String[] email, String title, String content) {
validateEmail(email);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setFrom(mailbox_server);
helper.setSubject(title);
helper.setText(content);
helper.setTo(email);
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(message);
}
public static void main(String[] args) {
String[] email = {"xx@xx.com","xx@xx.com"};//替换成自己的邮箱即可,可单个可多个
String title = "测试邮件";
String content = "测试内容";
sendEmail(email, title, content);
}
}
class EmailUtilException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
*
* @param message
*/
public EmailUtilException(String message) {
super(message);
}
/**
*
* @param message
* @param cause
*/
public EmailUtilException(String message, Throwable cause) {
super(message, cause);
}
/**
*
* @param cause
*/
public EmailUtilException(Throwable cause) {
super(cause);
}
}
***********************************如有附件*****************************
3.如果需要上传附件,可以将方法替换成如下代码,附件参数是filemap
public static void sendEmail(String[] email, String title, String content,Map<String,String> filemap) {
validateEmail(email);
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message,true);//设置为true
helper.setFrom(mailbox_server);
helper.setSubject(title);
helper.setText(content);
helper.setTo(email);
/*添加附件*/ //map中key为路径,value为对应附件名字
if(!filemap.isEmpty()){
for (Map.Entry<String,String> entry : filemap.entrySet()) {
File file = new File(entry.getKey());
FileSystemResource fileSource = new FileSystemResource(file);
helper.addAttachment(MimeUtility.encodeWord(entry.getValue()),fileSource);
}
}
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(message);
}
public static void main(String[] args) {
String[] email = {"xxx@xx.com"};
String title = "测试标题";
String content = "测试内容";
String files = "E:/ceshi.pdf";
Map<String,String> map = new HashMap<String, String>();
map.put(files, "测试附件.pdf");
sendEmail(email, title, content, map);
}
******************************************************************************************************
******************************************************************************************************
//封装的EmailInfo类,如有需要请关注一下代码:
import java.util.Arrays;
public class EmailInfo {
//邮件标题
private String title;
//邮件内容
private String mailContent;
//接收人
private String[] destination;
//邮件类型
private int type;
public EmailInfo(){
}
public EmailInfo(String title,String mailContent,String[] destination){
this.title = title;
this.mailContent = mailContent;
this.destination = destination;
}
public EmailInfo(String title,String mailContent,String[] destination,int type){
this.title = title;
this.mailContent = mailContent;
this.destination = destination;
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMailContent() {
return mailContent;
}
public void setMailContent(String mailContent) {
this.mailContent = mailContent;
}
public String[] getDestination() {
return destination;
}
public void setDestination(String[] destination) {
this.destination = destination;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "EmailInfo [title=" + title + ", mailContent=" + mailContent + ", destination="
+ Arrays.toString(destination) + ", type=" + type + "]";
}
}