Java Mail收集邮件的工具类PraseMimeMessage

这个工具类用于在使用Java Mail时,对message的内容提取,使提取我们所需要的内容更加方便,其中需要注意的点是:

        其中保存附件的方法(将附件可以保存在本地或者服务器中)。

public class PraseMimeMessage {
    private MimeMessage mimeMessage = null;

    private String saveAttachPath = "";

    private StringBuffer bodytext = new StringBuffer();

    private String dateformat = "yy-MM-dd HH:mm";

    private ArrayList<String> attachments = new ArrayList();

    private ArrayList<Long> attachSizeList = new ArrayList();

    private ArrayList<String> cidList = new ArrayList();

    public PraseMimeMessage() {
    }

    public PraseMimeMessage(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }
    /**
     * 邮箱来处
     * */
    public String getFrom()
            throws Exception {
        if (this.mimeMessage != null) {
            InternetAddress[] address = (InternetAddress[]) this.mimeMessage.getFrom();
            if (address.length < 1) {
                return "";
            }
            String from = address[0].getAddress();
            if (from == null) {
                from = "";
            }
            String personal = address[0].getPersonal();
            if (personal == null) {
                personal = "";
            }
            String fromaddr = personal + "<" + from + ">";
            return fromaddr;
        }
        return "";
    }
    /**
     * 获取邮件地址
     * */
    public String getMailAddress(String type)
            throws Exception {
        String mailaddr = "";
        if (this.mimeMessage != null) {
            String addtype = type.toUpperCase();
            InternetAddress[] address = null;
            if (("TO".equals(addtype)) || ("CC".equals(addtype)) || ("BCC".equals(addtype))) {
                if ("TO".equals(addtype))
                    address = (InternetAddress[]) this.mimeMessage.getRecipients(Message.RecipientType.TO);
                else if ("CC".equals(addtype))
                    address = (InternetAddress[]) this.mimeMessage.getRecipients(Message.RecipientType.CC);
                else {
                    address = (InternetAddress[]) this.mimeMessage.getRecipients(Message.RecipientType.BCC);
                }
                if ((address != null) && (address.length > 0)) {
                    for (int i = 0; i < address.length; ++i) {
                        String email = address[i].getAddress();
                        if (email == null)
                            email = "";
                        else {
                            email = MimeUtility.decodeText(email);
                        }
                        String personal = address[i].getPersonal();
                        if (personal == null)
                            personal = "";
                        else {
                            personal = MimeUtility.decodeText(personal);
                        }
                        String compositeto = personal + "<" + email + ">";
                        mailaddr = mailaddr + "," + compositeto;
                    }
                    mailaddr = mailaddr.substring(1);
                }
            } else {
                throw new Exception("Error emailaddr type!");
            }
        }
        return mailaddr;
    }
    /**
     * 获取目录
     * */
    public String getSubject()
            throws MessagingException {
        String subject = "";
        if (this.mimeMessage != null)
            try {
                subject = MimeUtility.decodeText(this.mimeMessage.getSubject());
                if (subject == null)
                    subject = "";
            } catch (Exception localException) {
            }
        return subject;
    }
    /**
     * 信息日期
     * */
    public Date getSentDate() {
        Date sentdate = new Date();
        try {
            if (this.mimeMessage != null)
                sentdate = this.mimeMessage.getSentDate();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        SimpleDateFormat format = new SimpleDateFormat(this.dateformat);
        return sentdate;
    }

    public String getBodyText() {
        return this.bodytext.toString();
    }
    /**
     * 获取邮件文本
     * */
    public void getMailContent(Part part)
            throws Exception {
        String contenttype = part.getContentType();
        if (contenttype.startsWith("text/plain")) {
            getMailTextContent(part, true);
        } else {
            getMailTextContent(part, false);
        }
    }
    /**
     * 文本内容信息
     * */
    public void getMailTextContent(Part part, boolean plainFlag)
            throws MessagingException, IOException {
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if ((part.isMimeType("text/html")) && (!isContainTextAttach) && (!plainFlag)) {
            this.bodytext.append(MimeUtility.decodeText(part.getContent().toString()));
        } else if ((part.isMimeType("text/plain")) && (!isContainTextAttach) && (plainFlag)) {
            this.bodytext.append(part.getContent().toString());
            plainFlag = false;
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), plainFlag);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; ++i) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, plainFlag);
            }
        }
    }
    /**
     * 获取信息ID
     * */
    public String getMessageId()
            throws MessagingException {
        if (this.mimeMessage != null) {
            return this.mimeMessage.getMessageID();
        }
        return null;
    }

    /**
     * 确定是否为新文件
     * */
    public boolean isNew()
            throws MessagingException {
        boolean isnew = false;
        if (this.mimeMessage != null) {
            Flags flags = this.mimeMessage.getFlags();
            Flags.Flag[] flag = flags.getSystemFlags();

            for (int i = 0; i < flag.length; ++i) {
                if (flag[i] == Flags.Flag.SEEN) {
                    isnew = true;

                    break;
                }
            }
        }
        return isnew;
    }

    /**
     * 附加标志
     */
    public boolean isContainAttach(Part part)
            throws Exception {
        boolean attachflag = false;
        if (part != null) {
            String contentType = part.getContentType();
            if (part.isMimeType("multipart/*")) {
                Multipart mp = (Multipart) part.getContent();
                for (int i = 0; i < mp.getCount(); ++i) {
                    BodyPart mpart = mp.getBodyPart(i);
                    String disposition = mpart.getDisposition();
                    if ((disposition != null) &&
                            (disposition.equals("attachment"))) {
                        attachflag = true;
                    } else {
                        if ((disposition != null) &&
                                (disposition.equals("inline")))
                            continue;
                        if (mpart.isMimeType("multipart/*")) {
                            attachflag = isContainAttach(mpart);
                        } else {
                            String contype = mpart.getContentType();
                            if (contype.toLowerCase().indexOf("application") != -1) {
                                attachflag = true;
                            }
                            if (contype.toLowerCase().indexOf("name") != -1)
                                attachflag = true;
                        }
                    }
                }
            } else if (part.isMimeType("message/rfc822")) {
                attachflag = isContainAttach((Part) part.getContent());
            }
        }
        return attachflag;
    }

    /**
     * 保存附件
     */
    public String saveAttachMent(Part part) throws Exception {
        System.out.println("login......saveAttachMent................");
        String fileName = "";

        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if ((disposition != null)
                        && ((disposition.equals(Part.ATTACHMENT)) || (disposition
                        .equals(Part.INLINE)))) {
                    fileName = mpart.getFileName();
                    System.out.println("打印拿到的附件名称------------------" + fileName);
                    System.out.println("经过mimeUtility解码后得到的:" + MimeUtility.decodeText(fileName));

                    //关键点:-----------------经过mimeUtility解码后可以得到正确的附件名称

                    // System.out.println("经过base64进行解码得到的:"+base64Decoder(fileName));
                    if (fileName.toLowerCase().indexOf("utf") != -1) {
                        fileName = MimeUtility.decodeText(fileName);
                    }
                    System.out.println("进行存储附件前的文件名称(1):" + fileName);

                    return saveFile(fileName, mpart.getInputStream());

                } else if (mpart.isMimeType("multipart/*")) {
                    saveAttachMent(mpart);
                } else {
                    fileName = mpart.getFileName();
                    if ((fileName != null) && (fileName.toLowerCase().indexOf("utf") != -1)) {
                        fileName = MimeUtility.decodeText(fileName);
                        System.out.println("进行存储附件前的文件名称(2):" + fileName);
                       return saveFile(fileName, mpart.getInputStream());
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachMent((Part) part.getContent());
        }
        return null;
    }

    //填写附件存入路径---------------------1
    public void setAttachPath(String attachpath) {
        this.saveAttachPath = attachpath;
    }

    public void setDateFormat(String format)
            throws Exception {
        this.dateformat = format;
    }

    public String getAttachPath() {
        return this.saveAttachPath;
    }

    /**
     * 保存附件到指定目录
     */
    private String saveFile(String fileName, InputStream in) throws Exception {
        /*String osName = System.getProperty("os.name");
        String storedir = getAttachPath();
        String separator = "";
        if (osName == null) osName = "";
        if (osName.toLowerCase().indexOf("win") != -1) {
            separator = "\\";
            if (storedir == null || storedir.equals(""))
                storedir = "c:\\tmp";
        } else {
            separator = "/";
            storedir = "/tmp";
        }*/
        File storefile = new File(getAttachPath()+ fileName);

        System.out.println("storefile's path: " + storefile.toString());

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(storefile));
            bis = new BufferedInputStream(in);
            int c;
            while ((c = bis.read()) != -1) {
                bos.write(c);
                bos.flush();
            }
            return storefile.toString();
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new Exception("文件保存失败!");
        } finally {
            bos.close();
            bis.close();
        }
    }

    public void resetList() {
        this.attachments.clear();
        this.attachSizeList.clear();
        this.cidList.clear();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="[email protected]">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
下面是一个简单的 Java 发送邮件工具类,你可以根据自己的需求进行修改: ``` import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; 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.MimeMessage; public class MailUtil { private String host; // 邮件服务器主机名 private String username; // 发件人账号 private String password; // 发件人密码 public MailUtil(String host, String username, String password) { this.host = host; this.username = username; this.password = password; } /** * 发送邮件 * @param to 收件人邮箱地址 * @param subject 邮件主题 * @param content 邮件内容 */ public void sendMail(String to, String subject, String content) throws MessagingException { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.host", host); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setContent(content, "text/html;charset=utf-8"); Transport.send(message); } } ``` 使用示例: ``` public static void main(String[] args) { String host = "smtp.163.com"; String username = "your_email@163.com"; String password = "your_email_password"; MailUtil mailUtil = new MailUtil(host, username, password); String to = "recipient_email@example.com"; String subject = "测试邮件"; String content = "这是一封测试邮件,如果你收到了,请回复我。"; try { mailUtil.sendMail(to, subject, content); System.out.println("邮件发送成功!"); } catch (MessagingException e) { System.out.println("邮件发送失败:" + e.getMessage()); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值