struts2集成javamail发邮件示例详解

一、代码预览
这两天在做struts2上的邮件发送。以前的项目有用到spring,用spring提供的邮件支持类很方便可以完成这个功能,但是现在只用struts2的话,就碰到了一系列的问题。

请先将自己下载的 mail.jar,及activation.jar加入到classpath

复制代码 代码如下:

package com.nerve.cloudoffice.common.util;

import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
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;

public class EMailSender {
     /**
     * 向用户发送邮件
     */
    private static final long serialVersionUID = 1L;

    private MimeMessage mimeMsg; // MIME邮件对象

    private Session session; // 邮件会话对象

    private Properties props; // 系统属性

    private boolean needAuth = false; // smtp是否需要认证

    private String username = ""; // smtp认证用户名和密码

    private String password = "";

    private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成

    private String log;

    public EMailSender() {

    }

    public EMailSender(String smtp) {
        setSmtpHost(smtp);
        createMimeMessage();
    }

    public void setSmtpHost(String hostName) {
        System.out.println("设置系统属性:mail.smtp.host = " + hostName);
        if (props == null)
            props = System.getProperties(); // 获得系统属性对象
        props.put("mail.smtp.host", hostName); // 设置SMTP主机
        props.put("mail.smtp.localhost", "localHostAdress");
    }

    public boolean createMimeMessage() {
        try {
            System.out.println("准备获取邮件会话对象!");
            session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
        } catch (Exception e) {
            log = "获取邮件会话对象时发生错误!" + e.toString();
            System.err.println(log);
            return false;
        }
        try {
            mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
            mp = new MimeMultipart(); // mp 一个multipart对象
            // Multipart is a container that holds multiple body parts.
            return true;
        } catch (Exception e) {
            log = "创建MIME邮件对象失败!" + e;
            System.err.println(log);
            return false;
        }
    }

    public void setNeedAuth(boolean need) {
        System.out.println("设置smtp身份认证:mail.smtp.auth = " + need);
        if (props == null)
            props = System.getProperties();
        if (need) {
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }
    }

    public void setNamePass(String name, String pass) {
        System.out.println("程序得到用户名与密码");
        username = name;
        password = pass;
    }

    public boolean setSubject(String mailSubject) {
        System.out.println("设置邮件主题!");
        try {
            mimeMsg.setSubject(MimeUtility.encodeText(mailSubject,"utf-8","B"));
            return true;
        } catch (Exception e) {
            log = "设置邮件主题发生错误!"+e;
            System.err.println(log);
            return false;
        }
    }

    public boolean setBody(String mailBody) {
        try {
            System.out.println("设置邮件体格式");
            BodyPart bp = new MimeBodyPart();
            // 转换成中文格式
            bp.setContent(
                    ""
                            + mailBody, "text/html;charset=utf-8");
            mp.addBodyPart(bp);
            return true;
        } catch (Exception e) {
            log = "设置邮件正文时发生错误!" + e;
            System.err.println(log);
            return false;
        }
    }

    public boolean setFiles(List files){
        try{
            for(String s:files){
                MimeBodyPart mbp=new MimeBodyPart(); 
                FileDataSource fds=new FileDataSource(s); //得到数据源 
                mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart 
                mbp.setFileName(fds.getName());  //得到文件名同样至入BodyPart 
                mp.addBodyPart(mbp);
            }
            return true;
        }catch(Exception e){
            log = "增加附件时出错:"+e;
            e.printStackTrace();
            return false;
        }
    }

    public boolean addFile(String path, String name){
        try{
            MimeBodyPart mbp=new MimeBodyPart(); 
            FileDataSource fds=new FileDataSource(path); //得到数据源 
            mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart 
            mbp.setFileName(MimeUtility.encodeText(name,"utf-8","B"));
            mp.addBodyPart(mbp);
            return true;
        }catch(Exception e){
            log = "增加附件时出错:"+e;
            e.printStackTrace();
            return false;
        }
    }

    public boolean setFrom(String from) {
        System.out.println("设置发信人!");
        try {
            mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
            return true;
        } catch (Exception e) {
            log = "设置发信人出错:"+e;
            return false;
        }
    }

    public boolean setTo(String to) {
        System.out.println("设置收信人");
        if (to == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
                    .parse(to));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean setCopyTo(String copyto) {
        if (copyto == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.CC,
                    (Address[]) InternetAddress.parse(copyto));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean sendout() {
        try {
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            System.out.println("正在发送邮件....");
            Session mailSession = Session.getInstance(props, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String) props.get("mail.smtp.host"), username,
                    password);
            transport.sendMessage(mimeMsg, mimeMsg
                    .getRecipients(Message.RecipientType.TO));
            // transport.send(mimeMsg);
            System.out.println("发送邮件成功!");
            transport.close();
            return true;
        } catch (Exception e) {
            log = "邮件发送失败!" + e;
            System.err.println(log);
            return false;
        }
    }

    public String getLog(){
        return log;
    }
}

二、问题总结

2.1  本地执行时报错

我用的是javaee 5,jdk1.6,在本地跑时,会出现ClassNotFound的Exception,但是这些类在mail.jar里面又是有的。这个原因是因为我们自己增加的jar包里面的类跟javaee5里面的冲突了,我推荐的解决方法是将javaee5里面的 activation包跟mail包删除。

做法如下:

找到eclipse引用的javaee5包,用rar软件打开,找到activation跟mail包,删除保存就可以了。(记得在ide中刷新一下引用包)

2.2 javax.mail.MessagingException: 501 Syntax: HELO hostname

在本地测试通过后,我部署到linux服务器中,但是去碰到了javax.mail.MessagingException: 501 Syntax: HELO hostname异常, google了发现是以下原因:

Javamail 在提取本地 hostname 的时候会 dig 改 hostname ,然后以改 ip 发送邮件。

由于 hostname 对应的 ip 地址, linux 无法解析(如果是 windows 则无这个问题, windows 利用 netbios 协议去获得该主机的 ip 地址)到本机 hostname 的 ip ,导致 javamail 无法调用发送 ip 。 Postfix 收到此类邮件将拒绝投递,而产生 501 错误。

网上说可以通过修改服务器的hosts文件解决,但是我发现还可以直接在代码里面解决(只需要加一行代码,这大大方便啊),即在setSmtpHost()方法中,增加下面一行:

复制代码 代码如下:

props.put("mail.smtp.localhost", "localHostAdress");

2.3 附件中文名乱码
如果附件有中文名,直接setName()会乱码,通过下面的方法可以解决:

复制代码 代码如下:

mbp.setFileName(MimeUtility.encodeText(name,"utf-8","B"));

你可能感兴趣的:(struts2集成javamail发邮件示例详解)