javamail 附件以及正文加图片
直接上代码
import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; 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.mail.util.ByteArrayDataSource; import org.apache.commons.httpclient.HttpException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Service; import com.cdp.api.onboarding.onboardingenum.AttachmentTypeEnum; @Service public class MailService { @Value("${ALIDM_SMTP_AUTH}") private String ALIDM_SMTP_AUTH; @Value("${ALIDM_SMTP_HOST}") private String ALIDM_SMTP_HOST; @Value("${ALIDM_SMTP_PORT}") private String ALIDM_SMTP_PORT; @Value("${ALIDM_SMTP_MAIL_USER}") private String ALIDM_SMTP_MAIL_USER; @Value("${ALIDM_SMTP_MAIL_PASSWORD}") private String ALIDM_SMTP_MAIL_PASSWORD; @Value("${ALIDM_SMTP_MAIL_FROM}") private String ALIDM_SMTP_MAIL_FROM; @Value("${ALIDM_SMTP_MAIL_FROM_PERSONAL}") private String ALIDM_SMTP_MAIL_FROM_PERSONAL; @Value("${ALIDM_SMTP_MAIL_FROM_CHARSET}") private String ALIDM_SMTP_MAIL_FROM_CHARSET; @Value("${ALIDM_SMTP_MAIL_REPLY}") private String ALIDM_SMTP_MAIL_REPLY; @Value("${QRCODEPICTUREURL}") private String ORCODEPATH; @Autowired private ResourceLoader resourceLoader; /** * 阿里云smtp邮件服务 * * @param mailTo * @param mailSubject * @param mailText * @param list * @throws MessagingException * @throws HttpException * @throws IOException */ public boolean sendMail(String mailTo, String mailSubject, String mailText) throws Exception { return sendMail(mailTo, mailSubject, mailText, null); } public boolean sendMail(String mailTo, String mailSubject, String mailText, List<Map<Integer, InputStream>> list) throws Exception { boolean flag = false; // 配置发送邮件的环境属性 final Properties props = new Properties(); // 表示SMTP发送邮件,需要进行身份验证 props.put("mail.smtp.auth", ALIDM_SMTP_AUTH); props.put("mail.smtp.host", ALIDM_SMTP_HOST); props.put("mail.smtp.port", ALIDM_SMTP_PORT); // 如果使用ssl,则去掉使用25端口的配置,进行如下配置, // props.put("mail.smtp.socketFactory.class", // "javax.net.ssl.SSLSocketFactory"); // props.put("mail.smtp.socketFactory.port", "465"); // props.put("mail.smtp.port", "465"); // 发件人的账号 props.put("mail.user", ALIDM_SMTP_MAIL_USER); // 访问SMTP服务时需要提供的密码 props.put("mail.password", ALIDM_SMTP_MAIL_PASSWORD); // 构建授权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // 用户名、密码 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用环境属性和授权信息,创建邮件会话 Session mailSession = Session.getInstance(props, authenticator); // mailSession.setDebug(true); // 创建邮件消息 MimeMessage message = new MimeMessage(mailSession); try { // 设置发件人 InternetAddress from = new InternetAddress(ALIDM_SMTP_MAIL_FROM, ALIDM_SMTP_MAIL_FROM_PERSONAL, ALIDM_SMTP_MAIL_FROM_CHARSET); message.setFrom(from); Address[] a = new Address[1]; a[0] = new InternetAddress(ALIDM_SMTP_MAIL_REPLY); message.setReplyTo(a); // 设置收件人 InternetAddress to = new InternetAddress(mailTo); message.setRecipient(MimeMessage.RecipientType.TO, to); // 设置邮件标题 message.setSubject(mailSubject); // 设置邮件的内容体 MimeMultipart mp = new MimeMultipart("related"); MimeBodyPart mbpContent = new MimeBodyPart(); // 判断模版是否要加二维码图片 if (mailText.contains("${MAIL_PHOTO}")) { mailText = mailText .replace("${MAIL_PHOTO}", "<img src=\"cid:image\" width='254' height='254' border='0'>"); mbpContent.setContent(mailText, "text/html; charset=utf-8"); mp.addBodyPart(mbpContent); InputStream ins = resourceLoader.getResource(ORCODEPATH).getInputStream(); DataSource dataSource4 = new ByteArrayDataSource(ins, "image/jpeg"); MimeBodyPart image = new MimeBodyPart(); DataHandler dataHandler4 = new DataHandler(dataSource4); image.setDataHandler(dataHandler4); image.setHeader("Content-ID", "image"); image.setFileName(dataHandler4.getName()); mp.addBodyPart(image); ins.close(); } else { mbpContent.setContent(mailText, "text/html; charset=utf-8"); mp.addBodyPart(mbpContent); } /* 往邮件中添加附件 */ if (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) { Map<Integer, InputStream> map = list.get(i);
//这里取了map的key值 Iterator<Integer> iter = map.keySet().iterator(); while (iter.hasNext()) { Integer key = Integer.parseInt(String.valueOf(iter .next())); InputStream ins = map.get(key);
//这里加了个枚举 switch (AttachmentTypeEnum.getByValue(key)) { case PNGJPG: MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.removeHeader("Content-Type"); messageBodyPart .removeHeader("Content-Transfer-Encoding"); messageBodyPart.addHeader("Content-Type", "text/html; charset=gbk"); messageBodyPart.addHeader( "Content-Transfer-Encoding", "base64"); DataSource dataSource1 = new ByteArrayDataSource( ins, "application/png"); DataHandler dataHandler1 = new DataHandler( dataSource1); messageBodyPart.setDataHandler(dataHandler1); messageBodyPart.setFileName(MimeUtility .encodeText("附件.jpg")); mp.addBodyPart(messageBodyPart); ins.close(); break; case WORD: MimeBodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.removeHeader("Content-Type"); messageBodyPart2 .removeHeader("Content-Transfer-Encoding"); messageBodyPart2.addHeader("Content-Type", "text/html; charset=gbk"); messageBodyPart2.addHeader( "Content-Transfer-Encoding", "base64"); DataSource dataSource2 = new ByteArrayDataSource( ins, "application/docx"); DataHandler dataHandler2 = new DataHandler( dataSource2); messageBodyPart2.setDataHandler(dataHandler2); messageBodyPart2.setFileName(MimeUtility .encodeText("附件.docx")); mp.addBodyPart(messageBodyPart2); ins.close(); break; case EXCEL: MimeBodyPart messageBodyPart3 = new MimeBodyPart(); messageBodyPart3.removeHeader("Content-Type"); messageBodyPart3 .removeHeader("Content-Transfer-Encoding"); messageBodyPart3.addHeader("Content-Type", "text/html; charset=gbk"); messageBodyPart3.addHeader( "Content-Transfer-Encoding", "base64"); DataSource dataSource3 = new ByteArrayDataSource( ins, "application/xlsx"); DataHandler dataHandler3 = new DataHandler( dataSource3); messageBodyPart3.setDataHandler(dataHandler3); messageBodyPart3.setFileName(MimeUtility .encodeText("附件.xlsx")); mp.addBodyPart(messageBodyPart3); ins.close(); break; case MAILPHOTO: MimeBodyPart image = new MimeBodyPart(); DataSource dataSource4 = new ByteArrayDataSource( ins, "image/jpeg"); DataHandler dataHandler4 = new DataHandler( dataSource4); image.setDataHandler(dataHandler4); image.setHeader("Content-ID", "a00000002"); image.setFileName(dataHandler4.getName()); mp.addBodyPart(image); ins.close(); break; } } } } message.setContent(mp); message.setSentDate(new Date()); // 发送邮件 Transport.send(message); flag = true; } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e.getMessage()); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e.getMessage()); } return flag; } }
有时在想 一直使用spring感觉会让自己越来越笨,各种写好的注解真的很方便啊