当前位置:主页 > 软件编程 > JAVA代码 >

Java实现批量发送带附件的邮件代码

时间:2023-01-11 10:46:20 | 栏目: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));
    }
}

总结

您可能感兴趣的文章:

相关文章