强大的java编程实现邮件发送功能,支持内容,上传多个图片和多个附件
来源:互联网 发布:览物之情得无异乎的乎 编辑:程序博客网 时间:2024/05/18 01:12
自己写的邮件发送功能,可以支持发送内容,发送多个图片和多个附件。
分享给大家,下面是我发送邮件的源码,贴过去用吧
首先准备一个Email对象,用于封装前台传递的数据。(如果你不需要前台的交互,可以不用这个对象)
package com.kewei.emailSender;import java.io.Serializable;public class Email implements Serializable {private String id;private String sender; // 发送人private String to; // 发给谁private String cc; // 抄送人 多个private String bcc; // 暗送人 多个private String subject; // 主题private String sendDate; // 发送时间private boolean replySign; // 要求回执private boolean containAttach; // 是否包含附件private String imagePath; // 邮件图片的路劲 (多个,使用"|"拼接)private String attachPath; // 邮件附件的路径 (多个,使用"|"拼接)private String content; // 邮件的文本内容private boolean isRead; // 是否已读public Email() {super();}public String getId() {return id;}public void setId(String id) {this.id = id;}public boolean isRead() {return isRead;}public void setRead(boolean isRead) {this.isRead = isRead;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getTo() {return to;}public void setTo(String to) {this.to = to;}public String getCc() {return cc;}public void setCc(String cc) {this.cc = cc;}public String getBcc() {return bcc;}public void setBcc(String bcc) {this.bcc = bcc;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getSendDate() {return sendDate;}public void setSendDate(String sendDate) {this.sendDate = sendDate;} public String getImagePath() {return imagePath;}public void setImagePath(String imagePath) {this.imagePath = imagePath; }public String getAttachPath() {return attachPath;}public void setAttachPath(String attachPath) {this.attachPath = attachPath;}public boolean isReplySign() {return replySign;}public void setReplySign(boolean replySign) {this.replySign = replySign;}public boolean isContainAttach() {return containAttach;}public void setContainAttach(boolean containAttach) {this.containAttach = containAttach;}public String getSender() {return sender;}public void setSender(String sender) {this.sender = sender;}}
根据类的单一职能原则,再准备一个EmailMessage对象,辅助邮件进行发送
package com.kewei.emailSender;import java.io.Serializable;import java.math.BigInteger;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Random;public class EmailMessage implements Serializable{private Email email;//邮件//private HttpServletRequest request;private String emailAccount; //发件人private String receiver; //收件人private String protocol; //使用协议private String host;//邮箱服务器private String auth;//是否请求认证private String username;//用户名private String password;//密码private String cc; // 抄送private String bcc; // 暗送private String subject; // 主题private String charset; // 字符编码private boolean receipt; // 回执private String content; // 文本private Map<String, String> map=new HashMap<String, String>(); //发送邮件处理图片所需的内容private List<String> attacPaths; //发送邮件附件/** * @return protocol */public String getProtocol() {return "smtp";}/** * @param protocol */public void setProtocol(String protocol) {this.protocol = protocol;}/** * @return host */public String getHost() {return EmailUtils.getMailServerHost(email.getSender());}/** * @param host */public void setHost(String host) {this.host = host;}/** * @return auth */public String getAuth() {return "true";}/** * @param auth */public void setAuth(String auth) {this.auth = auth;}/** * @return username */public String getUsername() {return this.username;}/** * @param username */public void setUsername(String username) {this.username = username;}/** * @return password */public String getPassword() {return this.password;}/** * @param password */public void setPassword(String password) {this.password = password;}/** * @return cc */public String getCc() {return email.getCc();}/** * @param cc */public void setCc(String cc) {this.cc = cc;}/** * @return bcc */public String getBcc() {return email.getBcc();}/** * @param bcc */public void setBcc(String bcc) {this.bcc = bcc;}/** * @return subject */public String getSubject() {return email.getSubject();}/** * @param subject */public void setSubject(String subject) {this.subject = subject;}/** * @return charset */public String getCharset() {return "UTF-8";}/** * @param charset */public void setCharset(String charset) {this.charset = charset;}public boolean isReceipt() {return email.isReplySign();}public void setReceipt(boolean receipt) {this.receipt = receipt;}/** * @return content */public String getContent() {if(map==null||map.size()==0){return email.getContent();}return content;}/** * @param content */public void setContent(String content) {this.content = content;}/** * @return emailAccount */public String getEmailAccount() {return email.getSender();}/** * @param emailAccount */public void setEmailAccount(String emailAccount) {this.emailAccount = emailAccount;}/** * @return receiver */public String getReceiver() {return email.getTo();}/** * @param receiver */public void setReceiver(String receiver) {this.receiver = receiver;}public Map<String, String> getMap() {//如果图片路径为null,直接返回nullif(email.getImagePath()==null||"".equals(email.getImagePath().trim())){return null;}StringBuffer sb=new StringBuffer();sb.append(email.getContent());//处理邮件中图片和附件的路径for (String realImgPath : email.getImagePath().split("\\|")) {String cid=genPK();//String cid=System.currentTimeMillis()+"";map.put(realImgPath, cid);sb.append("<br/><img src='cid:").append(cid).append("'").append("/>");}//设置文本setContent(sb.toString());return map;}public void setMap(Map<String, String> map) {this.map = map;}public List<String> getAttacPaths() {//如果附件路径为null,直接返回nullif(email.getAttachPath()==null||"".equals(email.getAttachPath().trim())){return null;}List<String> attachList=new ArrayList<String>();for (String realAttachPath : email.getAttachPath().split("\\|")) {attachList.add(realAttachPath);}return attachList;}public EmailMessage(Email email) {super();this.email = email;}public static String genPK() {return new BigInteger(165, new Random()).toString(36).toUpperCase();}}
提供一个EmailUtils 工具类,用于获取邮件服务器和验证邮件地址
package com.kewei.emailSender;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * @Description: 处理邮件的工具类 * @author huhao * @date Dec 26, 2013 5:32:38 PM */public class EmailUtils {private static Log logger = LogFactory.getLog(EmailUtils.class);// huhao19920306@163.com 通过@之后的是163还是qq,动态的判断邮件服务器pop.163.com// 994822422@qq.compublic static String getMailServerHost(String emailAddress) {if (emailAddress == null || "".equals(emailAddress.trim())) {throw new RuntimeException("邮件账户错误!");}StringBuffer sb = new StringBuffer();sb.append("smtp.");emailAddress = emailAddress.substring(emailAddress.lastIndexOf("@") + 1);sb.append(emailAddress);return sb.toString().trim();}// 验证邮箱地址public static boolean checkEmail(String email) {boolean flag = false;try {//String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";String check = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$";Pattern regex = Pattern.compile(check);Matcher matcher = regex.matcher(email);flag = matcher.matches();} catch (Exception e) {logger.error("邮箱地址错误!");flag = false;}return flag;}public static void main(String[] args) {System.out.println(checkEmail("1@163.ke.com"));}}
最后是一个邮件发送对象EmailSender,发送邮件就交给它了
package com.kewei.emailSender;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Map.Entry;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Authenticator;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;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;/** *@decrisption实现邮件的发送 *@author huhao *@version Nov 19, 2013 11:47:47 AM * @since JDK1.6.0_10 spring3.2.0 */public class MailSender {private MimeMessage msg;/** * @param msg */private EmailMessage emailMessage;public MailSender() {super();}/** * * 发送邮件,可发送多个图片和附件 *@author huhao * @date Nov 19, 2013 10:25:44 AM * @param ms * @throws EmailSendException * @throws UnsupportedEncodingException * */public void sendEmail(EmailMessage ms) {try {//得到环境对象getMimeMessage(ms); msg.setFrom(new InternetAddress(ms.getEmailAccount())); String [] receiverArray=ms.getReceiver().trim().split(",|,");//收件人InternetAddress数组InternetAddress [] receiverAddressArray=new InternetAddress[receiverArray.length];for (int i = 0; i < receiverArray.length; i++) { receiverAddressArray[i] =new InternetAddress(receiverArray[i].trim());}msg.setRecipients(MimeMessage.RecipientType.TO, receiverAddressArray); //设置收件人//暗送if(ms.getBcc()!=null && !"".equals(ms.getBcc().trim())){String [] bccArray=ms.getBcc().trim().split(",|,");InternetAddress [] bccAddressArray=new InternetAddress[bccArray.length];for (int i = 0; i < bccArray.length; i++) {bccAddressArray[i] =new InternetAddress(bccArray[i].trim());}msg.setRecipients(MimeMessage.RecipientType.BCC, bccAddressArray); }//抄送if(ms.getCc()!=null && !"".equals(ms.getCc().trim())){String [] ccArray=ms.getCc().trim().split(",|,");InternetAddress [] ccAddressArray=new InternetAddress[ccArray.length];for (int i = 0; i < ccArray.length; i++) {ccAddressArray[i] =new InternetAddress(ccArray[i].trim());}msg.setRecipients(MimeMessage.RecipientType.CC, ccAddressArray); }if(ms.isReceipt()){ //是否要求回执msg.setHeader("Disposition-Notification-To","1");msg.addHeader("Disposition-Notification-To", "1"); }msg.setSubject(ms.getSubject()); //主题MimeMultipart mmp = new MimeMultipart();Map<String, String> map=ms.getMap();//得到邮件内容if(map==null){mmp.addBodyPart(getTextPart(ms.getContent(), ms.getCharset()));}//得到所有的图片if(map!=null){ mmp.addBodyPart(getTextPart(ms.getContent(), ms.getCharset()));List<MimeBodyPart> imageParts=getImageParts(map);for (MimeBodyPart imagePart : imageParts) {mmp.addBodyPart(imagePart);}}//得到所有的附件List<String> attachPaths =ms.getAttacPaths();if(attachPaths!=null){List<MimeBodyPart> attchParts=getAttachmentParts(attachPaths);for (MimeBodyPart attchPart : attchParts) {mmp.addBodyPart(attchPart);}}msg.setSentDate(new Date()); mmp.setSubType("mixed");msg.setContent(mmp);msg.saveChanges();//保存修改//发送邮件Transport.send(msg);} catch (Exception e) {e.printStackTrace();}}/** * * 得到邮件的环境对象 *@author huhao * @date Nov 19, 2013 10:13:57 AM */public void getMimeMessage(EmailMessage ms){Properties props = new Properties();//设置一些参数:发送时需要设置props.setProperty("mail.transport.protocol", ms.getProtocol());props.setProperty("mail.host", ms.getHost());props.setProperty("mail.smtp.auth", ms.getAuth());//请求认证final String username=ms.getUsername();final String password=ms.getPassword();Session session = Session.getInstance(props,new Authenticator(){public PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username,password);}});//代表环境的对象msg = new MimeMessage(session);//得到了代表邮件的对象}/** * * 得到文本部分 *@author huhao * @date Nov 19, 2013 11:05:16 AM * @param content 文本内容(html代码) * @param charset 字符编码 * @return * @throws MessagingException * */public MimeBodyPart getTextPart(String content,String charset) throws MessagingException{MimeBodyPart textPart = new MimeBodyPart();textPart.setContent(content, "text/html;charset="+charset);return textPart;}/** * * 得到图片部分 *@author huhao * @date Nov 19, 2013 11:18:19 AM * @param map 代表的是文件路径和它所在的img标签的cid * @return * @throws MessagingException * */public List<MimeBodyPart> getImageParts(Map<String ,String> map) throws MessagingException{List<MimeBodyPart> imageParts=new ArrayList<MimeBodyPart>();for(Entry<String , String> e :map.entrySet()){MimeBodyPart imagePart = new MimeBodyPart();DataHandler dh = new DataHandler(new FileDataSource(e.getKey())); //jaf会自动探测文件的MIME类型imagePart.setDataHandler(dh);imagePart.setContentID(e.getValue());imageParts.add(imagePart);}return imageParts;}/** * * 得到附件部分 *@author huhao * @date Nov 19, 2013 11:22:36 AM * @param sources 多个附件的路径 * @return * @throws MessagingException * @throws UnsupportedEncodingException * */public List<MimeBodyPart> getAttachmentParts(List<String> sources) throws MessagingException, UnsupportedEncodingException{List<MimeBodyPart> attachmentParts=new ArrayList<MimeBodyPart>();for (String source : sources) {MimeBodyPart attachmentPart = new MimeBodyPart();DataHandler dh = new DataHandler(new FileDataSource(source));//jaf会自动探测文件的MIME类型String name = dh.getName();attachmentPart.setDataHandler(dh);attachmentPart.setFileName(MimeUtility.encodeText(name.substring(name.lastIndexOf("$^%")+3)));attachmentParts.add(attachmentPart);}return attachmentParts;}}
那么如何调用MailSender进行邮件的发送呢?
如果你需要和前端进行交互,可以使用email对象进行封装数据,在将email对象传递个emailMessage对象。
如果不需要的话,你可以修改一下我的代码。直接将数据传递给emailmessage对象。进行邮件的发送
0 0
- 强大的java编程实现邮件发送功能,支持内容,上传多个图片和多个附件
- Java发送邮件(支持多个附件)
- Python发送多个附件和支持HTML及纯文本内容的 Email 实现
- 发送邮件 支持添加多个附件
- java实现邮件抄送,密送,多个附件发送
- java实现 邮件抄送,密送,多个附件 发送
- 通过python发送带附件(支持多个附件)的邮件
- python发送邮件脚本(支持多个附件,中文)
- JavaMail实现带附件和图片的邮件发送功能
- python使用MIMEMultipart发送多个附件的邮件
- java发送带附件的邮件/附件图片显示在邮件内容中
- ASP.NET 实现发送邮件 + 多个收件人 + 多个附件
- javaMail发送邮件实例,支持附件和多人邮件的发送
- JAVA实现发送邮件(图片和附件)
- android 发送邮件(android自带email和javamail)均可发送带有多个附件
- 上传多个附件
- FileUpload 上传最大值和多个附件的上传
- java mail 发送多个附件
- c++ 类的继承与派生
- .NET开发不可错过的25款必备工具
- SCI论文快速发表
- poj1159(回文串+LCS+滚动数组)
- 英语学习笔记3:Pets
- 强大的java编程实现邮件发送功能,支持内容,上传多个图片和多个附件
- Error: [Microsoft][ODBC 驱动程序管理器] 在指定的 DSN 中,驱动程序和应用程序之间的体系结构不匹配
- LCD基础知识
- POJ 1637 混合图欧拉回路判定
- andriod 笔记__clipboardManager
- Android下屏保程序的 开发须知
- oracle (+) 左右关联
- 编译器报错: error LNK2001: unresolved external symbol "struct _ServiceDescriptorTable * KeServiceDescript
- 查询条件为ROWNUM=2没有结果