写在前面:
最近要将dms系统原始发邮件的功能(调用的webservice)改变成使用smtp服务来发送邮件(使用javamail来发送),这里简单记录下,方便日后有用到,直接拿来用即可。
首先导入需要用到的jar包:activation.jar mail.jar
涉及到的相关类:
直接上代码了:
TestMail.java
package dms.newmail; import java.util.Properties; import javax.mail.Session;
import javax.mail.Transport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping; public class TestMail { static String to = "cmm-dwcp-sw03@mail.foxconn.com";
static String cc = ""; public static void main(String[] args){
String subject = "【DMS邮件测试】";
String content = "Dear all,\n\n" +
" DMS邮件功能测试!\n";
MailService mailService = new MailServiceImpl();
try { mailService.sendMail(to, cc,subject, content); } catch (Exception e) { e.printStackTrace();
}
} }
如果是要在内容中含有超链接,只需要在内容中加上<html><body><a href=\"这里写链接\">测试</a></body></html>标签就好了(eg:<html><body><a href="http://10.203.70.189/spas">測試</a></body></html>)
MailService.java
package dms.newmail; public interface MailService {
/**
* 发送邮件
*
* @param to 接收人
* @param subject 邮件主题
* @param content 邮件内容
*/
void sendMail(String to, String subject, String content) throws Exception; void sendNoThreadMail(String to, String subject, String content); /**
* 发送邮件
* @param to 接收人
* @param cc 抄送人
* @param subject 邮件主题
* @param content 邮件内容
* @throws BusinessException
*/
void sendMail(String to, String cc,String subject, String content) throws Exception; }
MailServieImpl.java
package dms.newmail; import org.apache.log4j.Logger;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage; public class MailServiceImpl implements MailService {
private static Logger logger = Logger.getLogger(MailServiceImpl.class); public void sendMail(String to, String subject, String content) {
MailThread mailThread = new MailThread(to, subject, content);
System.out.println("to:" + to + "\nsubject:" + subject + "\n\ncontent:" + content);
mailThread.setName("發送" + to + "郵件");
mailThread.start(); } public void sendNoThreadMail(String to, String subject, String content) {
System.out.println("to:" + to + "\n,subject:" + subject + "\n\n,content:" + content);
MailUtil mailUtil = new MailUtil();
Session session = mailUtil.getSession();
MimeMessage message = null;
try {
message = mailUtil.createSimpleMessage(session, to, subject, content);
} catch (Exception e) {
logger.error("创建邮件失败");
}
try {
mailUtil.sendMessage(session, message);
} catch (MessagingException e) {
logger.error("连接不上SMTP服务器");
}
System.out.println("發送郵件成功");
} /**
* to:发送给(多个邮箱以;号隔开)
* cc:抄送(多个邮箱以;号隔开)
* subject:主题
* content:内容
*/
public void sendMail(String to, String cc, String subject, String content) throws Exception {
MailThread mailThread = new MailThread(to, cc,subject, content);
// System.out.println(to);
mailThread.setName("發送" + to + "郵件"+"抄送给"+to);
mailThread.start();
} }
MailThread.java
package dms.newmail; import org.apache.log4j.Logger; import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage; public class MailThread extends Thread {
private static Logger logger = Logger.getLogger(MailThread.class); private String to;
private String subject;
private String content;
private String cc; public MailThread() {
} public MailThread(String to, String subject, String content) {
this.to = to;
this.subject = subject;
this.content = content;
} public MailThread(String to, String cc, String subject, String content) {
this.to = to;
this.cc = cc;
this.subject = subject;
this.content = content;
} public void run() {
MailUtil mailUtil = new MailUtil();
Session session = mailUtil.getSession();
MimeMessage message = null;
try {
message = mailUtil.createSimpleMessage(session, to, cc, subject, content);
} catch (Exception e) {
logger.error("创建邮件失败");
}
try {
mailUtil.sendMessage(session, message);
} catch (MessagingException e) {
logger.error("连接不上SMTP服务器");
} System.out.println("發送郵件成功");
}
}
MailUtil.java
package dms.newmail; 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.MimeMessage;
import java.util.*; public class MailUtil {
//smtp服务器
public static final String SMTP_HOST = "10.134.28.95";
public static final String USER_NAME = "dmd.admin@foxconn.com";
public static final String PASS_WORD = "";
/**
* 获取邮件会话
*
* @return
*/
public Session getSession() {
Properties prop = new Properties();
prop.setProperty("mail.host", SMTP_HOST);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "false");
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
return session;
} /**
* 创建简单文本
*
* @param session
* @param to
* @param subject
* @param content
* @return
*/
public MimeMessage createSimpleMessage(Session session, String to, String subject, String content) throws Exception {
MimeMessage message = null;
message = getMessage(session, to, subject); message.setText(content, "UTF-8");
return message;
} public MimeMessage createSimpleMessage(Session session, String to, String cc, String subject, String content) throws Exception {
MimeMessage message = null;
if (cc == null || "".equals(cc)) {
message = getMessage(session, to, subject);
} else {
message = getMessage(session, to, cc, subject);
} message.setText(content, "UTF-8");
return message;
} /**
* 获取邮件对象
*
* @param session 邮件会话
* @param to 收件人
* @param subject 邮件主题
* @return
* @throws Exception
*/
private MimeMessage getMessage(Session session, String to, String subject) throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(USER_NAME));
String[] addresses = to.split(";");
Set addSet = new HashSet();
for(int i=0;i<addresses.length;i++){
if (!"".equals(addresses[i].trim()))
addSet.add(addresses[i].trim());
} InternetAddress[] internetAddresses = new InternetAddress[addSet.size()];
Iterator iterable = addSet.iterator();
for (int i = 0; i < addSet.size(); i++) {
internetAddresses[i] = new InternetAddress((String) iterable.next());
}
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipients(Message.RecipientType.TO, internetAddresses);
//邮件的标题
message.setSubject(subject, "UTF-8");
message.setSentDate(new Date(System.currentTimeMillis()));
//返回创建好的邮件对象
return message;
} /**
* @param session
* @param to 收件人
* @param cc 抄送人
* @param subject 邮件主题
* @return
* @throws Exception
*/
private MimeMessage getMessage(Session session, String to, String cc, String subject) throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(USER_NAME));
String[] addresses = to.split(";");
String[] addresses2 = cc.split(";");
Set addSet = new HashSet();
Set addSet2 = new HashSet();
for(int i=0;i<addresses.length;i++){
if (!"".equals(addresses[i].trim()))
addSet.add(addresses[i].trim());
}
for(int i=0;i<addresses2.length;i++){
if (!"".equals(addresses2[i].trim()))
addSet2.add(addresses2[i].trim());
} InternetAddress[] internetAddresses = new InternetAddress[addSet.size()];
Iterator iterable = addSet.iterator();
for (int i = 0; i < addSet.size(); i++) {
internetAddresses[i] = new InternetAddress((String) iterable.next());
}
InternetAddress[] internetAddresses2 = new InternetAddress[addSet2.size()];
Iterator iterable2 = addSet2.iterator();
for (int i = 0; i < addSet2.size(); i++) {
internetAddresses2[i] = new InternetAddress((String) iterable2.next());
}
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipients(Message.RecipientType.TO, internetAddresses);
message.setRecipients(Message.RecipientType.CC, internetAddresses2);
//邮件的标题
message.setSubject(subject, "UTF-8");
message.setSentDate(new Date(System.currentTimeMillis()));
//返回创建好的邮件对象
return message;
} /**
* 发送邮件
*
* @param session 邮件会话
* @param message 邮件
* @throws MessagingException
*/
public void sendMessage(Session session, Message message) throws MessagingException {
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
ts.connect(SMTP_HOST,USER_NAME,PASS_WORD);
// ts.connect();
//5、发送邮件
if (null != message)
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} }
LogUtil.java:
package dms.newmail; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.PrintWriter;
import java.io.StringWriter; public class LogUtil {
private static Logger logger = LoggerFactory.getLogger(LogUtil.class); public static String getTrace(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
throwable.printStackTrace(printWriter);
StringBuffer stringBuffer = stringWriter.getBuffer();
return stringBuffer.toString();
} public static void main(String[] args) {
String strTrace=getTrace(new Throwable());
System.out.println(strTrace); new Throwable().printStackTrace();
}
}
好啦,代码搬运完成啦~~~
这一块主要还是斌哥在spas写好的,这边dms用到我只是拿现成的啦~~
参考链接:https://www.cnblogs.com/xdp-gacl/p/4216311.html-----JavaWeb学习总结(五十二)——使用JavaMail创建邮件和发送邮件