java发送带附件邮件

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jcoapp;

/**
 *
 * @author luolai
 */
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

public class SendMailHelper {
    // defalt config

    private static String SMTP_HOST_NAME = "***.com.cn";
    private static String SMTP_AUTH_USER = "***";
    private static String SMTP_AUTH_PWD = "***";
    private static String emailMsgTxt = "text";
    private static String emailSubjectTxt = "Subject";
    private static String emailFromAddress = "***";
    // Add List of Email address to who email needs to be sent to
    private static String[] emailList = {"***"};
    
    private Configuration cf = new Configuration("logon.properties");

    public static void main(String args[]) throws Exception {
        SendMailHelper smtpMailSender = new SendMailHelper();
        smtpMailSender.postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
    }
    
    public void sendMail(String subject,String msgTxt){
        try {
            String email = cf.getValue("emailList");
            String[] emaillist = email.split(";");
            postMail(emaillist, subject, msgTxt, cf.getValue("emailFromAddress"));
        } catch (MessagingException ex) {
            Logger.getLogger(SendMailHelper.class.getName()).log(Level.SEVERE, null, ex);
            LogInfo.appendLog(ex.getMessage().toString());
        }
    }

    public void postMail(String recipients[], String subject,
            String message, String from) throws MessagingException {
        boolean debug = false;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);


        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain;charset=UTF-8");//text/plain
        Transport.send(msg);
    }
    
    public void sendAttachMail(String subject,String msgTxt,String[] attachFieNames){
        try {
            String email = cf.getValue("emailList");
            String[] emaillist = email.split(";");
            postAttachMail(emaillist, subject, msgTxt, cf.getValue("emailFromAddress"),attachFieNames);
        } catch (MessagingException ex) {
            Logger.getLogger(SendMailHelper.class.getName()).log(Level.SEVERE, null, ex);
            LogInfo.appendLog(ex.getMessage().toString());
        }
    }
    
    public void postAttachMail(String recipients[], String subject,
            String message, String from,String[] attachFieNames) throws MessagingException {
        boolean debug = false;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        
        Multipart m = new MimeMultipart();
        BodyPart body = new MimeBodyPart();
        DataSource source = new FileDataSource(new File(attachFieNames[0].toString()));
        body.setDataHandler(new DataHandler(source));
        try {
            body.setFileName(MimeUtility.encodeText(new File(attachFieNames[0].toString()).getName()));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SendMailHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
        m.addBodyPart(body);
        msg.setContent(m, "file");
        msg.setSentDate(new Date());   
        
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        //msg.setContent(message, "text/plain;charset=UTF-8");//text/plain
        
        Transport.send(msg);
    }

    /**
     * SimpleAuthenticator is used to do simple authentication when the SMTP
     * server requires it.
     */
    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }

    public static String getSMTP_HOST_NAME() {
        return SMTP_HOST_NAME;
    }

    public static void setSMTP_HOST_NAME(String smtp_host_name) {
        SMTP_HOST_NAME = smtp_host_name;
    }

    public static String getSMTP_AUTH_USER() {
        return SMTP_AUTH_USER;
    }

    public static void setSMTP_AUTH_USER(String smtp_auth_user) {
        SMTP_AUTH_USER = smtp_auth_user;
    }

    public static String getSMTP_AUTH_PWD() {
        return SMTP_AUTH_PWD;
    }

    public static void setSMTP_AUTH_PWD(String smtp_auth_pwd) {
        SMTP_AUTH_PWD = smtp_auth_pwd;
    }

    public static String getEmailMsgTxt() {
        return emailMsgTxt;
    }

    public static void setEmailMsgTxt(String emailMsgTxt) {
        SendMailHelper.emailMsgTxt = emailMsgTxt;
    }

    public static String getEmailSubjectTxt() {
        return emailSubjectTxt;
    }

    public static void setEmailSubjectTxt(String emailSubjectTxt) {
        SendMailHelper.emailSubjectTxt = emailSubjectTxt;
    }

    public static String getEmailFromAddress() {
        return emailFromAddress;
    }

    public static void setEmailFromAddress(String emailFromAddress) {
        SendMailHelper.emailFromAddress = emailFromAddress;
    }

    public static String[] getEmailList() {
        return emailList;
    }

    public static void setEmailList(String[] emailList) {
        SendMailHelper.emailList = emailList;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值