Java-发送邮件详细配置

添加配置文件:mail.properties

#邮件发送smtp
mail.send.host=smtp.sina.com.cn
#发送者
mail.send.from=systematq@sina.com
#邮件发送用户名
mail.send.user=systematq
#邮件发送密码
mail.send.password=XXXXXXX
#系统收件人 mail.server.user=systematq@sina.com # 编码 mail.smtp.encode=utf-8 #信息编码 mail.smtp.messageEncode=utf-8 #服务状态 1为启用,0为禁用 mail.smtp.status=1 #是否验证身份 mail.send.auth=true #模板地址 mail.model.address=/template/tool/sendEmailModel.ftl

 

 Java工具类

package com.ata.task;


/**
 * 邮件发�?�工具类
 * 
 * @author xxh
 * @link 
 * 
 * @version $Revision: 1.00 $ $Date: 2009-12-18
 */

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;





public class MailUtil {
    
    /*******
     * 邮件发�?�,带用户名和密码验证,测试通过
     * 
     * @param to
     * @param from
     * @param title
     * @param content
     * @param smtpServer
     * @param user
     * @param password
     * @throws AddressException
     * @throws MessagingException
     */
    @SuppressWarnings({"unchecked"})
    public static void send(String from, String to,String copyTo, String title,
            String content, String smtpServer, String user, String password,boolean isHTML)
            throws AddressException, MessagingException {
 
        Properties props = new Properties();
        Authenticator auth = new MailAuthenticator(user, password);
        Session sendMailSession;
        Transport transport;
        props.put("mail.smtp.host", smtpServer);
        props.put("mail.smtp.auth", "true");
        sendMailSession = Session.getInstance(props, auth);
        Message newMessage = new MimeMessage(sendMailSession);
        newMessage.setFrom(new InternetAddress(from));
        newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
                to));
        newMessage.addRecipient(Message.RecipientType.CC,new  InternetAddress(
                copyTo));
        newMessage.setSubject(title);
        newMessage.setSentDate(new Date());
        if (isHTML) {
            newMessage.setContent(content, "text/html;charset=UTF-8");
        } else {
            newMessage.setText(content);
        }
        transport = sendMailSession.getTransport("smtp");
        Transport.send(newMessage);
        transport.close();
        //System.out.println("---------- Mail Send Success ----------");
    }

    /*******************
     * 邮件发�?�,不带用户名和密码验证
     * @param to
     * @param from
     * @param title
     * @param content
     * @param smtpServer
     * @throws AddressException
     * @throws MessagingException
     */
    @SuppressWarnings("static-access")
    public static void send(String to, String from, String title,
            String content, String smtpServer) throws AddressException,
            MessagingException {
        Properties props = new Properties();
        Authenticator auth = new MailAuthenticator();
        Session sendMailSession;
        Transport transport;
        sendMailSession = Session.getInstance(props, auth);
        props.put("mail.smtp.host", smtpServer);
        props.put("mail.smtp.auth", "true");
        Message newMessage = new MimeMessage(sendMailSession);
        newMessage.setFrom(new InternetAddress(from));
        newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
                to));
        newMessage.setSubject(title);
        newMessage.setSentDate(new Date());
        newMessage.setText(content);
        transport = sendMailSession.getTransport("smtp");
        transport.send(newMessage);
    }

    /*********************
     * 带附件邮件发送,带用户名和密码验证,测试通过
     * @param to
     * @param from
     * @param title
     * @param content
     * @param smtpServer
     * @param user
     * @param password
     * @param fileNames
     * @param paths
     * @throws AddressException
     * @throws MessagingException
     */
    @SuppressWarnings("static-access")
    public static void send(String to, String from, String title,
            String content, String smtpServer, String user, String password,
            String fileNames[], String[] paths) throws AddressException,
            MessagingException {
        try {
            Properties props = new Properties();
            Authenticator auth = new MailAuthenticator(user, password);
            Session sendMailSession;
            Transport transport;
            props.put("mail.smtp.host", smtpServer);
            props.put("mail.smtp.auth", "true");
            sendMailSession = Session.getInstance(props, auth);
            MimeMessage newMessage = new MimeMessage(sendMailSession);
            newMessage.setFrom(new InternetAddress(from));
            newMessage.setRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));

            // 创建 Multipart 并放入每�? MimeBodyPart
            Multipart mp = new MimeMultipart();

            if (title != null && !title.equals("")) {
                // 设置邮件主题
                newMessage.setSubject(title);
            } else {
                newMessage.setSubject("无主�?");
            }
            // 第一部分信息
            MimeBodyPart mbp1 = new MimeBodyPart();
            if (content != null && !content.equals("")) {
                mbp1.setText(content, "GBK");
            } else {
                mbp1.setText(new String(), "GBK");
            }
            mp.addBodyPart(mbp1);

//            // 在第二部分信息中附加文件
//            if (paths != null) {
//                for (int i = 0; i < paths.length; i++) {
//                    MimeBodyPart mbp2 = new MimeBodyPart();
//                    FileDataSource fds = new FileDataSource(CommonConstants.ROOTPATH
//                            + paths[i]);
//                    mbp2.setDataHandler(new DataHandler(fds));
//                    mbp2.setFileName(fileNames[i]);
//                    mp.addBodyPart(mbp2);
//                }
//            }
            // 增加 Multipart 到信息体
            newMessage.setContent(mp);
            newMessage.setSentDate(new Date());
            transport = sendMailSession.getTransport("smtp");
            transport.send(newMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

class MailAuthenticator extends Authenticator {
    private String user;
    private String password;

    public MailAuthenticator() {

    }

    public MailAuthenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }


    
}

测试Java类:

 

package com.ata.task;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ata.model.sys.SysMailSend;
import com.ata.service.sys.MailSendServiceI;

/** * 邮件服务 * @author huo * */
@Component
public class AutoSendMail {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("mail");
    @Autowired
    private MailSendServiceI mailSendService;
    private static final int NotSendStat=0;//未发送
    private static final int SendedStat=1;//已发送
    private static final int SendFailStat=2;//失败
    public void doJob(){
        try {
            System.out.println("sendMail..................");
            List<SysMailSend> list=mailSendService.findSysMailSend(AutoSendMail.NotSendStat);
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                SysMailSend sysMailSend = (SysMailSend) iterator.next();
                sysMailSend.setPlanTime(new Timestamp(System.currentTimeMillis()));
                sysMailSend=this.sendMail(sysMailSend);
                mailSendService.updateSysMailSend(sysMailSend);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @param args
     */
    public  SysMailSend  sendMail(SysMailSend sysMailSend) {
        String mailHost = bundle.getString("mail.send.host");
        String from =  bundle.getString("mail.send.from");
        String mailUser  =bundle.getString("mail.send.user");
        String mailPassword = bundle.getString("mail.send.password");
        String to=sysMailSend.getSendTo();
        String copyTo=sysMailSend.getCopyTo();
        String title=sysMailSend.getMailTitle();
        String content=sysMailSend.getMailContent();
        sysMailSend.setFromAddr(from);
        try {
            sysMailSend.setSendTime(new Timestamp(System.currentTimeMillis()));
            MailUtil.send( from,to,copyTo,
                    title, content, mailHost, mailUser,
                    mailPassword, false);
            sysMailSend.setMailStat(AutoSendMail.SendedStat);
            System.out.println("Mail Send Success");
            return sysMailSend;
        } catch (AddressException e) {
            System.out.println("AddressException-------" + e.getMessage());
            e.printStackTrace();
            sysMailSend.setMailStat(AutoSendMail.SendFailStat);
            return sysMailSend;
        } catch (MessagingException e) {
            System.out.println("MessagingException-------" + e.getMessage());
            e.printStackTrace();
            sysMailSend.setMailStat(AutoSendMail.SendFailStat);
            return sysMailSend;
        }
    }
}

 

posted @ 2013-11-09 17:21  霍哥  阅读(2372)  评论(0编辑  收藏  举报