您的位置:首页 > 其它

【笔记】发送邮件工具类的使用

2017-03-25 08:46 381 查看

【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");
/*QQ邮箱要开启ssl加密*/
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);

// 使用JavaMail发送邮件的5个步骤
// 1、创建session
Session session = Session.getInstance(prop);
// 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
// 2、通过session得到transport对象
Transport ts = session.getTransport();
// 3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
ts.connect(stmp, userName, passWord);
System.out.println("邮件连接初始化成功===================");
// 4、创建邮件
Message message = createGroupMixedMail(session, absPath, title,content,tos,copyTos,attachments);
System.out.println("创建邮件成功===================");
// 5、发送邮件
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();
//String subject = new String(base64.encode((title).getBytes("UTF-8")));
//message.setSubject("=?UTF-8?B?" + subject + "?=");
message.setSubject(MimeUtility.encodeText(title, "UTF-8", "B"));
// message.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
//message.setSubject(title);

// 正文
MimeBodyPart text = new MimeBodyPart();
if(content.contains("\r\n")){
content=content.replace("\r\n","<br>");
}
text.setContent(conten
4000
t,
"text/html;charset=UTF-8");

// 附件1
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);
}
}
// 代表正文的bodypart
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对象
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];
//用于存放收件人(通知人)的id
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");
//如果类型是1,发送邮件并添加发送邮件记录,否则,添加工作空间通知
if(shape.equals("1")){

boolean b=SendMail.sendOut(absPath, mailTitle, mailContent, tos, copyTos, fileNames);
if(b){
//获取发送人id
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"> 
<!--避免ajax请求出现406错误-->
<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>

<!-- spring分发器控制文件 -->
<!-- 扫描action层 多个action之间 可以用逗号隔开 -->
<context:component-scan base-package="*"></context:component-scan>

<!--    <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
cafd

value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix">
<value>/WEB-INF/project/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"/>
</bean>

</beans>


谢谢支持!

资源下载:http://download.csdn.net/detail/jul_11th/9793192

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: