Java實現批量發送帶附件的郵件代碼

前言

       新功能上線時要經常發包到測試或生產服務器進行模塊部署,但由於安全限制隻能通過郵件傳輸小於10M的附件這種方式把jar包上傳到服務器。所以往往要發送幾十個郵件手動發送比較麻煩,偷懶寫瞭個粘貼即用的Demo,如有不足,請多指教! 

實體類(註意註釋)

代碼詳情如下:

package Email;
/*
* 參數實體類
* */
public class EmailParameter {
    //發信郵箱
    private String fromMailbox;
    //發信郵箱密碼(獨立郵箱填寫密碼,163或qq等第三方郵箱填寫授權碼)
    private String fromMailboxPWD;
    //收信郵箱
    private String toMailbox;
    //附件在本機下的目錄路徑
    private String enclosurePath;
    //郵箱主機(如QQ郵箱是smtp.qq.com、163郵箱是smtp.163.com)
    private String host;
    //與上一次發送郵件間隔時間 默認5秒
    private long sleepTime = 5000;
    //郵件發送成功後給本地文件打的成功標識
    private String successTag;
 
    public String getSuccessTag() {
        return successTag;
    }
 
    public void setSuccessTag(String successTag) {
        this.successTag = successTag;
    }
 
    public String getFromMailbox() {
        return fromMailbox;
    }
 
    public void setFromMailbox(String fromMailbox) {
        this.fromMailbox = fromMailbox;
    }
 
    public String getFromMailboxPWD() {
        return fromMailboxPWD;
    }
 
    public void setFromMailboxPWD(String fromMailboxPWD) {
        this.fromMailboxPWD = fromMailboxPWD;
    }
 
    public String getToMailbox() {
        return toMailbox;
    }
 
    public void setToMailbox(String toMailbox) {
        this.toMailbox = toMailbox;
    }
 
    public String getEnclosurePath() {
        return enclosurePath;
    }
 
    public void setEnclosurePath(String enclosurePath) {
        this.enclosurePath = enclosurePath;
    }
 
    public String getHost() {
        return host;
    }
 
    public void setHost(String host) {
        this.host = host;
    }
 
    public long getSleepTime() {
        return sleepTime;
    }
 
    public void setSleepTime(long sleepTime) {
        this.sleepTime = sleepTime;
    }
 
    @Override
    public String toString() {
        return "EmailParameter{" +
                "fromMailbox='" + fromMailbox + '\'' +
                ", fromMailboxPWD='" + fromMailboxPWD + '\'' +
                ", toMailbox='" + toMailbox + '\'' +
                ", enclosurePath='" + enclosurePath + '\'' +
                ", host='" + host + '\'' +
                ", sleepTime=" + sleepTime +
                ", successTag='" + successTag + '\'' +
                '}';
    }
}

實現類

       在確認程序運行完或發送故障報錯後那些本地郵件已被發送那些本地文件未被發送時,我代碼中用的是修改文件名的方式。這種方式方便但會有弊端,當你要發送的附件文件為被分卷切分後的文件時,文件名被修改會導致該分卷切分文件不能被正常解壓提取。建議用生成txt文件的方式記錄已發送文件的文件名。

代碼詳情如下:

package Email;
 
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.util.StringUtils;
 
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* 編輯並發送郵件Service
* */
public class EmailsServiceImpl {
    public String sendEmails(EmailParameter parameter){
        if(!this.isMailbox(parameter.getFromMailbox())){
            return "發信郵箱格式不正確";
        }
        if(!this.isMailbox(parameter.getToMailbox())){
            return "收信郵箱格式不正確";
        }
        try{
            //獲取郵件主機系統屬性
            Properties properties = System.getProperties();
            //設置郵件服務器
            properties.setProperty("mail.smtp.host", parameter.getHost());
            properties.put("mail.smtp.auth", "true");
            MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
            sslSocketFactory.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
            //獲取session
            Session session = Session.getDefaultInstance(properties,new Authenticator(){
                public PasswordAuthentication getPasswordAuthentication() {
                    //發件人賬號密碼
                    return new PasswordAuthentication(parameter.getFromMailbox(), parameter.getFromMailboxPWD());
                }
            });
            //附件所在的目錄路徑
            File fileUrl = new File(parameter.getEnclosurePath());
            //獲取目錄下的所有文件(可以在.listFiles()方法中使用匿名內部類重寫accept()方法針對文件名對文件進行過濾)
            File fileList [] = fileUrl.listFiles();
            //已發送郵件數
            int currentNum = 1;
            if(StringUtils.isEmpty(fileList)){
                return "文件夾"+parameter.getEnclosurePath()+"內容為空";
            }
            for(File file : fileList){
                //待發送郵件數
                int surplusNum = fileList.length-currentNum;
                //創建郵件
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(parameter.getFromMailbox()));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(parameter.getToMailbox()));
                //郵件名命名
                message.setSubject(file.getName());
                //郵件文本
                BodyPart messageBodyPart = new MimeBodyPart();
                String text=String.format("本次共將發送郵件%s封-已發送%s封-待發送%s封", fileList.length,currentNum,surplusNum);
                messageBodyPart.setText(text);
                //郵件內容
                Multipart multipart = new MimeMultipart();
                //將郵件文本放進郵件內容中
                multipart.addBodyPart(messageBodyPart);
                //郵件附件
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                messageBodyPart.setDataHandler(new DataHandler(source));
                //附件名命名
                messageBodyPart.setFileName(MimeUtility.encodeText(file.getName()));
                //將附件放進郵件內容中
                multipart.addBodyPart(messageBodyPart);
                //將郵件內容放進郵件中
                message.setContent(multipart);
                //發送
                Transport.send(message);
                //發送成功後將作為附件的本地文件名添加上成功標識,防止發送郵件中程序意外終止後無法區分已發送和未發送(用時間戳區分批次順序用currentNum區分在本批次中的順序)
                File newFileName = new File(file.getParent() + File.separator + String.format("%s_%s_%s",parameter.getSuccessTag(),currentNum,file.getName()));
                file.renameTo(newFileName);
                currentNum++;
                System.out.println(text+"|已發送文件:"+file.getName());
                //增加時間散列防止被第三方郵箱系統檢測為垃圾郵箱
                Thread.sleep(parameter.getSleepTime());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "發送成功";
    }
 
    //郵箱驗證
    public boolean isMailbox(String mailbox){
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(mailbox);
        boolean result = matcher.matches();
        return result;
    }
}

 方法中調用,詳情如下:

package Email;
 
public class Email {
    public static void main(String[] args) throws Exception {
        EmailParameter emailParameter = new EmailParameter();
        emailParameter.setFromMailbox("******@163.com");
        emailParameter.setFromMailboxPWD("******");
        emailParameter.setToMailbox("******@qq.com");
        emailParameter.setEnclosurePath("C:\\Users\\ly\\Desktop\\email");
        emailParameter.setHost("smtp.163.com");
        emailParameter.setSleepTime(5000);
        emailParameter.setSuccessTag("ss");
        System.out.println(new EmailsServiceImpl().sendEmails(emailParameter));
    }
}

總結

到此這篇關於Java實現批量發送帶附件的郵件代碼的文章就介紹到這瞭,更多相關Java發送帶附件的郵件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: