简单实现Jmail发送邮件

package com.chauvet.util;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

/**
 * 用于发送jmail邮件 
 * 需要用到 SMTPAuthenticator.java
 * @author WXW
 * 
 */
public class Jmail {
    private String hostSmtp = "smtp.126.com"; // 邮箱smtp
    private String hostAddress = "*******@126.com"; // 发件箱地址
    private String hostPwd = "pwd"; // 发件箱密码
    private static Logger log = Logger.getLogger(Jmail.class.getName());

    /**
     * 发送jmail
     * 
     * @param title
     *            email标题
     * @param content
     *            Email内容
     * @param toAddress
     *            接收邮箱地址 如:514725202@qq.com
     */
    public void sendMail(String title, String content, String toAddress) {
        try {
            String mail = content;
            // properties里面包含发送邮件服务器的地址
            Properties mailProps = new Properties();
            mailProps.put("mail.smtp.host", hostSmtp);
            mailProps.put("mail.smtp.auth", "true");
            SMTPAuthenticator smtpAuthenticator = new SMTPAuthenticator(hostAddress, hostPwd);
            Session mailSession = Session.getDefaultInstance(mailProps,smtpAuthenticator);
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(new InternetAddress(hostAddress));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, false));
            message.setSubject(title);
            message.setText(mail);
            Transport.send(message);
        } catch (Exception exc) {
            log.error("发送邮件 "+title+" 异常!");
            exc.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Jmail aa = new Jmail();
        aa.sendMail("标题", "内容", "514725202@qq.com");
        System.out.println("Well Done!");
    }
}

 

posted @ 2016-08-09 10:15  wxw_wang  阅读(861)  评论(0编辑  收藏  举报
/* 下雪 begin */ /* 下雪 end */ /* 点击出现爱心特效 begin*/ /* 点击出现爱心特效 end*/