欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

struts2集成javamail发邮件示例详解

程序员文章站 2022-07-12 08:27:38
一、代码预览这两天在做struts2上的邮件发送。以前的项目有用到spring,用spring提供的邮件支持类很方便可以完成这个功能,但是现在只用struts2的话,就碰到...

一、代码预览
这两天在做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(
                    "<meta http-equiv=content-type content=text/html; charset=utf-8>"
                            + 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<string> 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"));