以下程序需要3个jar包的支持:
javax.mail-1.5.1.jar
activation-1.1.1.jar
org.springframework.context.support-3.x.x.RELEASE.jar
applicationContext.xml中的代码如下:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host"> <value>smtp.126.com</value> </property> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.timeout">25000</prop> </props> </property> <property name="username"> <value>testmyname</value> </property> <property name="password"> <value>xxxxxx</value> </property> </bean>
TestJavaMailSend.java代码如下:
import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; 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.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; public class TestJavaMailSend { public static void main(String[] args) throws MessagingException { ApplicationContext ctx = new FileSystemXmlApplicationContext("src-resources/applicationContext.xml"); JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); TestJavaMailSend javaMailSend = new TestJavaMailSend(); //测试发送只有文本信息的简单测试 javaMailSend.sendTextMail(sender); //测试发送HTML内容的邮件 javaMailSend.sendHtmlMail(sender); //测试发送带附件的邮件 javaMailSend.sendMimeMessage(sender); } /** * 测试发送只有文本信息的简单测试 * @param sender 邮件发送器 * @throws Exception */ private void sendTextMail(JavaMailSender sender) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo("[email protected]"); mail.setFrom("[email protected]"); mail.setSubject("我是中文邮件主题!"); mail.setText("spring Mail的简单!@#$%$%^%&^^%&*()\":|}OIYUDS~~<>?\":DFGSDSD测试"); sender.send(mail); System.out.println("成功发送文本邮件!"); } /** * 测试发送HTML内容的邮件 * @param sender 邮件发送器 * @throws MessagingException * @throws Exception */ private void sendHtmlMail(JavaMailSender sender) throws MessagingException { MimeMessage msg = sender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8"); message.setFrom("[email protected]"); message.setSubject("我是中文HTML邮件主题"); message.setTo("[email protected]"); //这个地方传入数组可以发送给多人 //message.setCc("[email protected]"); //抄送地址,传入数组也可以抄送多人 String htmlContent = "<html><head><title>htmlttt</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body><table border=\"1\"><tr><td>第一列</td><td>第二列</td></tr><tr><td colspan=\"2\"><img src=\"cid:shihuantp\"></td></tr></table></body></html>"; message.setText(htmlContent, true); //如果发的不是html内容去掉true参数 // add the image (图片会嵌入到邮件里显示出来) FileSystemResource image = new FileSystemResource(new File("H:/我的像册/摇大旗.JPG")); message.addInline("shihuantp", image); //这里的shihuantp一定要跟<img src=\"cid:shihuantp\">中cid后面的值一样 sender.send(msg); System.out.println("成功发送Html邮件!"); } /** * 发送带附件的邮件 * @param sender 邮件发送器 * @throws Exception */ private void sendMimeMessage(final JavaMailSender sender) { //附件文件集合 final List files = new ArrayList(); MimeMessagePreparator mimeMail = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException, UnsupportedEncodingException { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); mimeMessage.setFrom(new InternetAddress("[email protected]")); mimeMessage.setSubject("Spring发送带附件的邮件-修改了附件编码", "UTF-8"); Multipart mp = new MimeMultipart(); //向Multipart添加正文 MimeBodyPart content = new MimeBodyPart(); content.setText("内含spring邮件发送的例子,请查收!"); //向MimeMessage添加(Multipart代表正文) mp.addBodyPart(content); files.add("H:/myfiledirectpry/velocity-1.7.jar"); files.add("H:/myfiledirectpry/commons-email-1.3.2-bin.zip"); files.add("H:/myfiledirectpry/我的备忘录.xls"); //向Multipart添加附件 Iterator it = files.iterator(); while(it.hasNext()) { MimeBodyPart attachFile = new MimeBodyPart(); String filename = it.next().toString(); FileDataSource fds = new FileDataSource(filename); attachFile.setDataHandler(new DataHandler(fds)); attachFile.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachFile); } files.clear(); //向Multipart添加MimeMessage mimeMessage.setContent(mp); mimeMessage.setSentDate(new Date()); } }; //发送带附件的邮件 sender.send(mimeMail); System.out.println("成功发送带附件邮件!"); } }
上面的TestJavaMailSend.java是笔者做测试用的,下面笔者对测试的代码进行了封装:
package com.shihuan.core.common.mail; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; 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 javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; public class SendEmail { protected static Logger logger = LoggerFactory.getLogger(SendEmail.class); /** * 功能: 发送只有文本信息的简单测试 * @param request HttpServletRequest对象 * @param fromSender 发送方地址 (例如: [email protected]) * @param toDestination 接收方地址 (例如: [email protected]) * @param emailSubject 邮件主题 * @param emailContent 邮件正文 (例如: "你好!I am Student!") */ public static void sendTextMail(HttpServletRequest request, String fromSender, String toDestination, String emailSubject, String emailContent) { ApplicationContext ctx = (ApplicationContext) request.getSession().getServletContext().getAttribute("ac"); JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); SimpleMailMessage mail = new SimpleMailMessage(); mail.setFrom(fromSender); mail.setTo(toDestination); mail.setSubject(emailSubject); mail.setText(emailContent); sender.send(mail); logger.info("成功发送文本邮件!"); } /** * 功能: 发送HTML内容的邮件 * @param request HttpServletRequest对象 * @param fromSender 发送方地址 (例如: [email protected]) * @param toDestination 接收方地址 (例如: [email protected]) * @param emailSubject 邮件主题 * @param emailContent 邮件正文 (例如: "<html><head><title>htmlttt</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body><table border=\"1\"><tr><td>第一列</td><td>第二列</td></tr><tr><td colspan=\"2\"><img src=\"cid:shihuantp\"></td></tr></table></body></html>") * @param imageMap 在邮件中预显示的图片 (例如: map.put("shihuantp", "E:/我的像册/摇大旗.JPG"); map.put("mtytp", "E:/我的像册/海豚馆.JPG");) * @throws MessagingException */ public static void sendHtmlMail(HttpServletRequest request, String fromSender, String toDestination, String emailSubject, String emailContent, Map<String, String> imageMap) throws MessagingException { ApplicationContext ctx = (ApplicationContext) request.getSession().getServletContext().getAttribute("ac"); JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); MimeMessage msg = sender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8"); message.setFrom(fromSender); message.setTo(toDestination); message.setSubject(emailSubject); // String htmlContent = "<html><head><title>htmlttt</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body><table border=\"1\"><tr><td>第一列</td><td>第二列</td></tr><tr><td colspan=\"2\"><img src=\"cid:shihuantp\"></td></tr></table></body></html>"; message.setText(emailContent, true); //如果发的不是html内容去掉true参数 // add the image (图片会嵌入到邮件里显示出来) //FileSystemResource image = new FileSystemResource(new File("E:/我的像册/摇大旗.JPG")); //message.addInline("shihuantp", image); //这里的shihuantp一定要跟<img src=\"cid:shihuantp\">中cid后面的值一样 FileSystemResource image = null; Iterator iter = imageMap.keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); String value = imageMap.get(key); image = new FileSystemResource(new File(value)); message.addInline(key, image); } sender.send(msg); logger.info("成功发送Html邮件!"); } /** * 功能: 发送带附件的邮件 * @param request HttpServletRequest对象 * @param fromSender 发送方地址 (例如: [email protected]) * @param toDestination 接收方地址 (例如: [email protected]) * @param emailSubject 邮件主题 * @param emailContent 邮件正文 (例如: "你好!I am Student!") * @param attachments 邮件附件的绝对路径 (例如: new String[]{"E:/myserver/velocity-1.7.jar", "E:/myserver/commons-email-1.3.2-bin.zip", "E:/myserver/我的备忘录.xls"}) */ public static void sendMimeMessage(HttpServletRequest request, final String fromSender, final String toDestination, final String emailSubject, final String emailContent, final String[] attachments) { ApplicationContext ctx = (ApplicationContext) request.getSession().getServletContext().getAttribute("ac"); JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); //附件文件集合 final List files = new ArrayList(); MimeMessagePreparator mimeMail = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException, UnsupportedEncodingException { mimeMessage.setFrom(new InternetAddress(fromSender)); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toDestination)); mimeMessage.setSubject(emailSubject, "UTF-8"); Multipart mp = new MimeMultipart(); //向Multipart添加正文 MimeBodyPart content = new MimeBodyPart(); content.setText(emailContent); //向MimeMessage添加(Multipart代表正文) mp.addBodyPart(content); for (int i = 0; i < attachments.length; i++) { files.add(attachments[i]); } //向Multipart添加附件 Iterator it = files.iterator(); while(it.hasNext()) { MimeBodyPart attachFile = new MimeBodyPart(); String filename = it.next().toString(); FileDataSource fds = new FileDataSource(filename); attachFile.setDataHandler(new DataHandler(fds)); attachFile.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachFile); } files.clear(); //向Multipart添加MimeMessage mimeMessage.setContent(mp); mimeMessage.setSentDate(new Date()); } }; //发送带附件的邮件 sender.send(mimeMail); logger.info("成功发送带附件邮件!"); } }