前言:在原<a target=_blank href="http://blog.csdn.net/qq_34328832/article/details/52162959" style="cursor: pointer;">java邮件发送</a>做了改进,新添功能,如:群发,发图片,和带附件发送
package com.base.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
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;
/**
* 邮件发送公用类
* @author Administrator
*
*/
public class MailSendUtil {
/**
* 常见的邮件发送协议地址
*/
// public static final String SMTP_QQ = "smtp.qq.com";
// public static final String SMTP_163 = "smtp.163.com";
// public static final String SMTP_126 = "smtp.126.com";
// public static final String SMTP_SINA = "smtp.sina.com";
// public static final String SMTP_GMAIL = "smtp.gmail.com";
//发送的信息
private MimeMessage message;
//邮件会话
private Session session;
//邮件发送
private Transport transport;
private String mailHost="";
private String sender_username="";
private String sender_password="";
private Properties properties = new Properties();
/**
* 初始化方法
* @param debug
*/
public MailSendUtil(boolean debug) {
InputStream in = MailSendUtil.class.getResourceAsStream("/MailServer.properties");
try {
properties.load(in);
this.mailHost = properties.getProperty("mail.smtp.host");
this.sender_username = properties.getProperty("mail.sender.username");
this.sender_password = properties.getProperty("mail.sender.password");
} catch (IOException e) {
e.printStackTrace();
}
session = Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message = new MimeMessage(session);
}
public MailSendUtil(boolean debug,String username,String pwd){
String type = username.substring(username.indexOf("@")+1, username.length());
String host = "smtp."+type;
try {
mailHost = host;
sender_username = username;
sender_password = pwd;
} catch (Exception e) {
e.printStackTrace();
}
// session.setDebug(debug);//开启后有调试信息
message = new MimeMessage(session);
}
/**
* 发送邮件
*
* @param subject 邮件主题
* @param sendHtml 邮件内容
* @param receiveUser 收件人地址
*/
public void doSendHtmlEmail(String subject, String sendHtml,
String receiveUser) {
try {
// 发件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
InternetAddress from = new InternetAddress(MimeUtility.encodeWord("JavaEamil")+" <"+sender_username+">");
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);//还可以有CC、BCC
// 邮件主题
message.setSubject(subject);
String content = sendHtml.toString();
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=UTF-8");
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
/**
* 群发邮件
* 默认
* @param subject 邮件主题
* @param sendHtml 邮件内容
* @param stringArr 收件人地址
*/
public boolean doSendHtmlEmails(String subject, String sendHtml,
String[] stringArr) {
boolean iflag = false;
try {
// 发件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
InternetAddress from = new InternetAddress(MimeUtility.encodeWord("JavaEamil")+" <"+sender_username+">");
message.setFrom(from);
// 设置收件人们
final int num = stringArr.length;
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
// addresses[i] = new InternetAddress(stringArr[i]);
if(null != stringArr[i]){
addresses[i] = new InternetAddress(stringArr[i]);
}
}
message.setRecipients(Message.RecipientType.TO, addresses);
// 邮件主题
message.setSubject(subject);
String content = sendHtml.toString();
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=UTF-8");
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
iflag = true;
} catch (Exception e) {
e.printStackTrace();
iflag = false;
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return iflag;
}
/**
* 群发邮件
* 非默认
* @param subject 邮件主题
* @param sendHtml 邮件内容
* @param stringArr 收件人地址
*/
public boolean doSendHtmlEmailsBy(String subject, String sendHtml,
String[] stringArr) {
boolean iflag = false;
try {
// 发件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
InternetAddress from = new InternetAddress(MimeUtility.encodeWord("JavaEamil")+" <"+sender_username+">");
message.setFrom(from);
// 设置收件人们
final int num = stringArr.length;
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
// addresses[i] = new InternetAddress(stringArr[i]);
if(null != stringArr[i]){
addresses[i] = new InternetAddress(stringArr[i]);
}
}
message.setRecipients(Message.RecipientType.TO, addresses);
// 邮件主题
message.setSubject(subject);
String content = sendHtml.toString();
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=UTF-8");
// 保存邮件
message.saveChanges();
//transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
iflag = true;
} catch (Exception e) {
e.printStackTrace();
iflag = false;
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return iflag;
}
/**
* 群发邮件 带图片
* @param subject
* @param sendHtml
* @param stringArr
* @param img
* @return
* @throws Exception
*/
public boolean createImageMail (String subject, String sendHtml,
String[] stringArr,String img) throws Exception{
boolean iflag = false;
try {
// 发件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
InternetAddress from = new InternetAddress(MimeUtility.encodeWord("JavaEamil")+" <"+sender_username+">");
message.setFrom(from);
// 设置收件人们
final int num = stringArr.length;
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
// addresses[i] = new InternetAddress(stringArr[i]);
if(null != stringArr[i]){
addresses[i] = new InternetAddress(stringArr[i]);
}
}
message.setRecipients(Message.RecipientType.TO, addresses);
// 邮件主题
message.setSubject(subject);
// 准备邮件数据
// 准备邮件正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:xxx.jpg'>的邮件", "text/html;charset=UTF-8");
// 准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(img));
image.setDataHandler(dh);
image.setContentID("xxx.jpg");
// 描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
message.setContent(mm);
message.saveChanges();
//将创建好的邮件写入到E盘以文件的形式进行保存
message.writeTo(new FileOutputStream("E:\\ImageMail.eml"));
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
iflag = true;
}catch (Exception e) {
e.printStackTrace();
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return iflag;
}
/**
* 创建一封带附件的邮件
* 默认
* @param subject
* @param sendHtml
* @param stringArr
* @param file
* @return
* @throws Exception
*/
public boolean createAttachMail(String subject, String sendHtml,
String[] stringArr,String file) throws Exception{
boolean iflag = false;
try {
// 发件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面这个是设置发送人的Nick name
InternetAddress from = new InternetAddress(MimeUtility.encodeWord("JavaEamil")+" <"+sender_username+">");
message.setFrom(from);
// 设置收件人们
final int num = stringArr.length;
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
// addresses[i] = new InternetAddress(stringArr[i]);
if(null != stringArr[i]){
addresses[i] = new InternetAddress(stringArr[i]);
}
}
message.setRecipients(Message.RecipientType.TO, addresses);
// 邮件主题
message.setSubject(subject);
//创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
MimeBodyPart text = new MimeBodyPart();
text.setContent(sendHtml, "text/html;charset=UTF-8");
//创建邮件附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(file));
attach.setDataHandler(dh);
attach.setFileName(dh.getName());
//创建容器描述数据关系
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(attach);
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
//将创建的Email写入到E盘存储
// message.writeTo(new FileOutputStream("E:\\attachMail.eml"));
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
iflag = true;
}catch (Exception e) {
e.printStackTrace();
iflag = false;
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
iflag = false;
}
}
}
return iflag;
}
/**
* 生成一封带附件和带图片的邮件
* @param subject
* @param sendHtml
* @param stringArr
* @param file
* @param img
* @return
* @throws Exception
*/
public boolean createMixedMail(String subject, String sendHtml,
String[] stringArr,File file,String img) throws Exception {
boolean iflag = false;
try {
//正文
MimeBodyPart text = new MimeBodyPart();
text.setContent(sendHtml,"text/html;charset=UTF-8");
//图片
MimeBodyPart image = new MimeBodyPart();
image.setDataHandler(new DataHandler(new FileDataSource(img)));
image.setContentID(img);
//附件1
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(file));
attach.setDataHandler(dh);
attach.setFileName(dh.getName());
//描述关系:正文和图片
MimeMultipart mp1 = new MimeMultipart();
mp1.addBodyPart(text);
mp1.addBodyPart(image);
mp1.setSubType("related");
//描述关系:正文和附件
MimeMultipart mp2 = new MimeMultipart();
mp2.addBodyPart(attach);
//代表正文的bodypart
MimeBodyPart content = new MimeBodyPart();
content.setContent(mp1);
mp2.addBodyPart(content);
mp2.setSubType("mixed");
message.setContent(mp2);
message.saveChanges();
//将创建的Email写入到E盘存储
// message.writeTo(new FileOutputStream("E:\\attachMail.eml"));
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
iflag = true;
}catch (Exception e) {
e.printStackTrace();
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return iflag;
}
}
另外由于发送图片涉及图片上传,在这奉上
/**
* 图片上传
* @param file
* @param request
* @return
*/
public String fileupload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){
//获取工作路径
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
System.out.println(path);
//保存
try {
//创建图片储存目录
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
file.transferTo(targetFile);
} else{
file.transferTo(targetFile);
}
} catch (Exception e) {
e.printStackTrace();
}
String fileUrl = path+"\\"+fileName;
return fileUrl;
}
jsp 页面:关于图片上传的(部分)
<input type="file" name="file" id="file" size="15" enctype="multipart/form-data" accept="image/jpg,image/png">
另外注意 :1.表单提交 记得注明 method="post" enctype="multipart/form-data" ,
小提示:处了基本功能 ----- 邮件发送,以外,自己可以再做一点功能的补充,像一些表单验证之类的
这里介绍一下自己的:
1.因为表单内容是使用的是 textarea ,所以这里做了一个字数限制的js
js
//限制文本域输入字数
function checkLen(obj) {
var maxChars = 600;//最多字符数
if (obj.value.length > maxChars)
obj.value = obj.value.substring(0, maxChars);
var curr = maxChars - obj.value.length;
document.getElementById("count").innerHTML = curr.toString();
}
jsp
<textarea id="content" name="content" rows="" cols="175"
style="overflow-y: auto; overflow-x: hidden;border: 1px solid #cad8e5;"
class="edit_area js_editorArea" placeholder="*内容..."οnchange="this.value=this.value.substring(0, 600)"
οnkeydοwn="this.value=this.value.substring(0, 600)"
οnkeyup="checkLen(this)"></textarea>
最后:自我感觉功能上有些地方还是欠缺的,有意见的欢迎小伙伴们指出