项目中经常用到发送邮件的功能,用来提示客户任务情况。
一下代码是关于项目中用到的一些关于发送邮件的代码。
package com.cnooc.filenet.services; import java.text.SimpleDateFormat; import java.util.Date; import javax.mail.Message; import javax.mail.Multipart; 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 org.springframework.stereotype.Service; import filenet.vw.api.VWException; import filenet.vw.api.VWSession; /** * @ClassName: MailService * @Description: 邮件发送服务 */ @Service public class MailService { public void sendMail(VWSession mailVWSession, String from, String to, String cc, String subject, String body) { try { if(to == null || "".equalsIgnoreCase(to)){ System.out.println("The email address of to must be a valid value"); throw new VWException("MailService.sendMail", "The email address of to must be a valid value"); } Session mailSession = mailVWSession.createMailSession(); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from, MimeUtility.encodeText("系统邮件", "gb2312", "b"))); if(cc != null && (cc.length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); Multipart multipart = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(body, "UTF-8"); mimeBodyPart.setHeader("Content-Type", "text/html;charset=UTF-8"); try { multipart.addBodyPart(mimeBodyPart); msg.setContent(multipart); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); System.out.println("send mail failed. " + e.getMessage()); } System.out.println("send mail succussfully"); } catch (Exception e) { e.printStackTrace(); } }
下面是邮件的内容部分,这部分是自己拼写的,根据自己的项目情况来确定
public String getMailBody(String to, String content, String link){ String mailBody = ""; mailBody += to; mailBody += ",您好"; mailBody += "<br/>"; mailBody += " XX系统,您有任务:" + content; mailBody += ",请登录系统查看。"; mailBody += "<br/>"; mailBody += "<br/>"; mailBody += "<a href='" + link + "'>点此进入系统</a>"; mailBody += "<br/>"; mailBody += "<br/>"; mailBody += "XX办公平台系统"; mailBody += "<br/>"; mailBody += new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); return mailBody; } }
当初自己不会写关于邮件这部分的东西,知道项目中有该需求,而且功能已经实现自己就兴奋的找到代码。并查阅了一些资料自己了解了一下。这是之前的总结的一些内容,好久没遇到关于邮件的需求了,今天把这些写下来也简单的回忆一下。