【utils】
package com.athl.utils;
import java.io.FileOutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import com.sun.mail.util.MailSSLSocketFactory;
import sun.misc.BASE64Encoder;
/**
* 文件名:SendMail.java
* 描述:发送邮件
* 修改人: lzy
* 修改时间:2017-03-18
* 修改内容:
* 1.stmp、userName、passWord、from的值
* 2.createGroupMixedMail函数中,添加判断附件是否为null
* 3.createGroupMixedMail函数中,添加判断抄送是否为null
* 4.添加QQ邮箱开启ssl加密
* 5.添加main函数测试
* 6.添加附件路径 absPath+"/"
*/
public class SendMail {
private static String stmp = "smtp.qq.com";
private static String userName = "2744664xxx";
private static String passWord = "oharpnpsedpsdfxcx";
private static String from = "2744664xxx@qq.com";
/**
* @param args
* @return
* @throws Exception
*/
public static boolean sendOut(String absPath,String title,String content,String[] tos ,String[] copyTos,String[] attachments) throws Exception {
boolean suc = false;
try {
Properties prop = new Properties();
prop.setProperty("mail.host", stmp);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(prop);
session.setDebug(true);
Transport ts = session.getTransport();
ts.connect(stmp, userName, passWord);
System.out.println("邮件连接初始化成功===================");
Message message = createGroupMixedMail(session, absPath, title,content,tos,copyTos,attachments);
System.out.println("创建邮件成功===================");
ts.sendMessage(message, message.getAllRecipients());
System.out.println("发送邮件成功===================");
suc = true;
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
return suc;
}
/**
* @Method: createGroupMixedMail
* @Description: 生成一封群发带附件和带图片的邮件
* @param session
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
public static MimeMessage createGroupMixedMail(Session session,String absPath,String title,String content,String[] tos ,String[] copyTos,String[] attachments) throws Exception {
MimeMessage message = new MimeMessage(session);
String toList = getMailList(tos);
@SuppressWarnings("static-access")
InternetAddress[] recipients = new InternetAddress().parse(toList);
if(copyTos!=null && copyTos[0]!=null){
Address[] addresses = new InternetAddress[copyTos.length];
for (int i = 0; i < copyTos.length; i++) {
addresses[i] = new InternetAddress(copyTos[i]);
}
message.setRecipients(Message.RecipientType.CC, addresses);
}
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,recipients);
sun.misc.BASE64Encoder base64 = new BASE64Encoder();
message.setSubject(MimeUtility.encodeText(title, "UTF-8", "B"));
MimeBodyPart text = new MimeBodyPart();
if(content.contains("\r\n")){
content=content.replace("\r\n","<br>");
}
text.setContent(content,
"text/html;charset=UTF-8");
MimeBodyPart attach = new MimeBodyPart();
MimeMultipart mp = new MimeMultipart();
if(attachments!=null && attachments[0]!=null){
for (String atta : attachments) {
attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(absPath+"/"+atta));
attach.setDataHandler(dh);
attach.setFileName(MimeUtility.encodeText(dh.getName(), "UTF-8", "B"));
mp.addBodyPart(attach);
}
}
mp.addBodyPart(text);
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));
return message;
}
/**
* @Method: getMailList
* @Description: 将收件人地址数组拼接成以逗号分隔的字符串
* @param mailArray
* @return String
* @throws null
*/
private static String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
public static void main(String[] args) {
String[] s={"2744664xxx@qq.com"};
try {
sendOut(null,"Holle","你好!这是一封测试邮件!",s,null,null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
【action】
/**
* 发送邮件,并添加发送邮件记录
* @param m
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/insertSendLog.html")
public String insertSendLog(Model m,MultipartFile attachments,HttpServletRequest request,HttpSession session) throws Exception {
List<UserInfo> list=userInfoService.findAllUserInfo();
String inpTo=request.getParameter("inpTo");
if(inpTo=="" || inpTo==null){
return "redirect:initSendLog.html";
}
String[] toNames=inpTo.split(",");
String inpCopyTo=request.getParameter("inpCopyTo");
String[] copyToNames=null;
String[] copyTos=null;
if(inpCopyTo!=null || inpCopyTo!=""){
copyToNames=inpCopyTo.split(",");
copyTos=new String[copyToNames.length];
int j=0;
for(UserInfo user:list){
for(String copyToName:copyToNames){
if(user.getUsername().equals(copyToName)){
copyTos[j]=user.getEmail();
j++;
}
}
}
}
String[] tos=new String[toNames.length];
StringBuffer toIds=new StringBuffer();
int i=0;
for(UserInfo user:list){
for(String toName:toNames){
if(user.getUsername().equals(toName)){
tos[i]=user.getEmail();
toIds.append(user.getUserId());
if(i!=toNames.length-1){
toIds.append(",");
}
i++;
}
}
}
String mailTitle= request.getParameter("mailTitle");
String absPath=null;
String[] fileNames=new String[1];
if(!attachments.isEmpty()){
absPath=session.getServletContext().getRealPath("/WEB-INF/upload");
String fileName = attachments.getOriginalFilename();
fileNames[0]=fileName;
File file = new File(absPath,fileName);
attachments.transferTo(file);
}
String mailContent = request.getParameter("mailContent");
String shape = request.getParameter("shape");
if(shape.equals("1")){
boolean b=SendMail.sendOut(absPath, mailTitle, mailContent, tos, copyTos, fileNames);
if(b){
String strId=((UserInfo)request.getSession().getAttribute("User")).getUserId();
sendLogService.insertSendLog(new SendLog(UuidUtil.get32UUID(),toIds.toString(),mailContent,2,strId,DateUtil.getTime()));
}
}else{
messageService.insertMsg(new Message(UuidUtil.get32UUID(),6,"11",mailContent,toIds.toString(),DateUtil.getTime()));
}
return "redirect:initSendLog.html";
}
【config】
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false"/>
<property name="favorParameter" value="false"/>
<property name="ignoreAcceptHeader" value="false"/>
<property name="mediaTypes">
<value>
atom = application/atom+xml
html = text/html
json = application/json
* = */*
</value>
</property>
</bean>
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list><value>text/json;charset=UTF-8</value></list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="*"></context:component-scan>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"/>
</bean>
</beans>
谢谢支持!