当前位置: 移动技术网 > IT编程>开发语言>Java > Java邮件发送

Java邮件发送

2019年04月04日  | 移动技术网IT编程  | 我要评论

package com...util;

import java.util.properties;
import javax.activation.datahandler;
import javax.activation.filedatasource;
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 mailutil {
private mimemessage mimemsg; // mime邮件对象
private session session; // 邮件会话对象
private properties props; // 系统属性
private boolean needauth = false; // smtp是否需要认证
// smtp认证用户名和密码
private string username;
private string password;
private multipart mp; // multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成mimemessage对象

/**
 * constructor
 * 
 * @param smtp
 *            邮件发送服务器
 */
public mailutil(string smtp){ 
    setsmtphost(smtp); 
    createmimemessage(); 
} 

/**
 * 设置邮件发送服务器
 * 
 * @param hostname
 *            string
 */
public  void setsmtphost(string hostname) { 
    // system.out.println("设置系统属性:mail.smtp.host = "+hostname);
    if(props == null)
        props = system.getproperties(); // 获得系统属性对象
    props.setproperty("mail.smtp.socketfactory.class",
            "javax.net.ssl.sslsocketfactory");

    props.setproperty("mail.smtp.socketfactory.fallback", "false");

    props.put("mail.smtp.host", hostname); // 设置smtp主机
    props.setproperty("mail.smtp.port", "465");//qq设置465///25

} 


/**
 * 创建mime邮件对象
 * 
 * @return
 */
public boolean createmimemessage() 
{ 
    try { 
        // system.out.println("准备获取邮件会话对象!");
        session = session.getdefaultinstance(props, null); // 获得邮件会话对象
        session.setdebug(true);
    } 
    catch(exception e){ 
        system.err.println("获取邮件会话对象时发生错误!" + e);
        return false; 
    } 

    // system.out.println("准备创建mime邮件对象!");
    try { 
        mimemsg = new mimemessage(session); // 创建mime邮件对象
        mp = new mimemultipart(); 
    
        return true; 
    } catch(exception e){ 
        system.err.println("创建mime邮件对象失败!" + e);
        return false; 
    } 
}   

/**
 * 设置smtp是否需要验证
 * 
 * @param need
 */
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"); 
    } 
} 

/**
 * 设置用户名和密码
 * 
 * @param name
 * @param pass
 */
public void setnamepass(string name,string pass) { 
    username = name; 
    password = pass; 
} 

/**
 * 设置邮件主题
 * 
 * @param mailsubject
 * @return
 */
public boolean setsubject(string mailsubject) { 
    // system.out.println("设置邮件主题!");
    try{ 
        mimemsg.setsubject(mailsubject); 
        return true; 
    } 
    catch(exception e) { 
        system.err.println("设置邮件主题发生错误!");
        return false; 
    } 
}

/**
 * 设置邮件正文
 * 
 * @param mailbody
 *            string
 */ 
public boolean setbody(string mailbody) { 
    try{ 
        bodypart bp = new mimebodypart(); 
        bp.setcontent(""+mailbody,"text/html;charset=gbk"); 
        mp.addbodypart(bp); 
        return true; 
    } catch(exception e){ 
        system.err.println("设置邮件正文时发生错误!" + e);
    return false; 
    } 
} 

/**
 * 添加附件
 * 
 * @param filename
 *            string
 */ 
public boolean addfileaffix(string filename) { 

    // system.out.println("增加邮件附件:"+filename);
    try{ 
        bodypart bp = new mimebodypart(); 
        filedatasource fileds = new filedatasource(filename); 
        bp.setdatahandler(new datahandler(fileds)); 
        bp.setfilename(mimeutility.encodetext(fileds.getname()));       
        mp.addbodypart(bp); 
        return true; 
    } catch(exception e){ 
        system.err.println("增加邮件附件:" + filename + "发生错误!" + e);
        return false; 
    } 
} 

/**
 * 设置发信人
 * 
 * @param from
 *            string
 */ 
public boolean setfrom(string from) { 
    // system.out.println("设置发信人!");
    try{ 
        
        mimemsg.setfrom(new internetaddress(from)); // 设置发信人
        
        return true; 
    } catch(exception e) { 
        return false; 
    } 
} 

/**
 * 设置收信人
 * 
 *  设置属性
 *  private properties p; // p是属性集合类,用来设置邮件的一些属性比如timeout等
 *  p.put("username","xxx@163.com"); //这里填上你的邮箱(发送方)
 *  构件mimemessage 对象,并设置在发送给收信人之前给自己(发送方)抄送一份
 *  mimemessage msg = mailsender.createmimemessage();
 *  msg.addrecipients(mimemessage.recipienttype.cc, internetaddress.parse(p.getproperty("username")));
 *
 * @param to
 *            string
 */ 
public boolean setto(string[] to,string from){ 
    if(to == null)return false; 
    
    try{ 
        mimemsg.addrecipients(message.recipienttype.cc,internetaddress.parse(from));//给自己抄送一份
        
        int mailsize = to.length;
        for(int i = 0; i < mailsize; i++){
            internetaddress tostr = new  internetaddress(to[i]);
            mimemsg.addrecipients(message.recipienttype.to, internetaddress.parse(tostr.tostring()));
        }
        
        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.getallrecipients());
        transport.sendmessage(mimemsg,mimemsg.getrecipients(message.recipienttype.cc));
        transport.sendmessage(mimemsg,mimemsg.getrecipients(message.recipienttype.to));
         system.out.println("发送邮件成功!");
        transport.close();          
        return true; 
    } catch(exception e) { 
        system.err.println("邮件发送失败!" + e);
        return false; 
    } 
} 

/**
 * 调用sendout方法完成邮件发送
 * 
 * @param smtp
 * @param from
 * @param to
 * @param subject
 * @param content
 * @param username
 * @param password
 * @return boolean
 */
public static boolean send(string smtp,string from,string[] to,string subject,string content,string username,string password) {
    mailutil themail = new mailutil(smtp);
    themail.setneedauth(true); // 需要验证
    
    if(!themail.setsubject(subject)) return false;
    if(!themail.setbody(content)) return false;
    if(!themail.setto(to,from)) return false;
    if(!themail.setfrom(from)) return false;
    themail.setnamepass(username,password);
    
    if(!themail.sendout()) return false;
    return true;
}

/**
 * 调用sendout方法完成邮件发送,带附件
 * 
 * @param smtp
 * @param from
 * @param to
 * @param subject
 * @param content
 * @param username
 * @param password
 * @param filename
 *            附件路径
 * @return
 */
public static boolean send(string smtp,string from,string[] to,string subject,string content,string username,string password,string filename) {
    mailutil themail = new mailutil(smtp);
    themail.setneedauth(true); // 需要验证
    
    if(!themail.setsubject(subject)) return false;
    if(!themail.setbody(content)) return false;
    if(!themail.addfileaffix(filename)) return false; 
    if(!themail.setto(to,from)) return false;
    if(!themail.setfrom(from)) return false;
    themail.setnamepass(username,password);
    if(!themail.sendout()) return false;
    return true;
}

}
测试类
// mail.host=smtp.163.com
// mail.from=*****@163.com
// mail.username=****@163.com//邮箱地址
// mail.password=****//邮箱密码
public class mailtest {
public static void main(string[] args) {
string host = "smtp.aliyun.com";
string from = "****@aliyun.com";
string[] touser = new string[]{"******@qq.com"};
string subject = "测试邮件发送";
string username = "****";
string password = "****";
string content = "测试发送内容";
boolean falg = mailutil.send(host, from, touser, subject, content,username, password);
system.out.println(falg);
}

}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网