美文网首页工作小记
javaMail发送qq邮件(二):可发送抄送密送多人,支持附件

javaMail发送qq邮件(二):可发送抄送密送多人,支持附件

作者: 叫子非鱼啊 | 来源:发表于2020-03-26 21:31 被阅读0次

    关于javaMail发送邮件的详细教程可以看Java 发送邮件(菜鸟教程)本文的基础代码也来自这里。

    关于实现的效果图如下

    Snipaste_2020-03-25_18-05-06.png Snipaste_2020-03-25_18-06-44.png Snipaste_2020-03-25_18-09-25.png Snipaste_2020-03-25_18-12-12.png

    在网上看到有说发送QQ邮箱需要添加SSL加密的代码

    // 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.ssl.socketFactory", sf);
    

    但在测试的时候发现不用开启SSL加密也能发送成功。

    如何添加多个收件人

                InternetAddress[] addArr = null;
                // 设置收件人
                addArr = new InternetAddress[toList.size()];
                for (int i = 0; i < toList.size(); i++) {
                    String mailtoString = (String) toList.get(i);
                    addArr[i] = new InternetAddress(mailtoString);
                }
                message.setRecipients(Message.RecipientType.TO, addArr); // 设置收件人地址
    

    抄送人和密送人类似,更改Message.RecipientType.TOMessage.RecipientType.CC(抄送)和Message.RecipientType.BCC(密送即可)

    如何发送附件

    需要在创建MimeMessage对象后

                // 创建默认的 MimeMessage 对象
                MimeMessage message = new MimeMessage(session);
    

    设置消息体的文件数据
    代码如下

                    // 带有附件的邮件发送
                    MimeMultipart multi = new MimeMultipart();
                    BodyPart bodyPartText = new MimeBodyPart();
                    bodyPartText.setText(messageContent); // 设置邮件内容
                    multi.addBodyPart(bodyPartText);
                    String fileName = null;
                    for (int i = 0; i < fileList.size(); i++) {
                        fileName = (String) fileList.get(i);
                        FileDataSource fds = new FileDataSource(fileName);
                        
                        BodyPart fileBodyPart = new MimeBodyPart();
                        fileBodyPart.setDataHandler(new DataHandler(fds));  // 设置附件文件数据
                        
                        fileBodyPart.setFileName(fds.getName()); // 设置附件文件名称
                        multi.addBodyPart(fileBodyPart);
                    }
                    message.setContent(multi);
    

    发送邮件的整体代码

    import java.io.UnsupportedEncodingException;
    import java.util.Date;
    import java.util.Properties;
    import java.util.Vector;
    
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Authenticator;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    
    /**
     * 发送邮件服务
     * 
     * @author lxh96
     *
     */
    public class SendEmailService {
        private String mailServerPort = "25"; // 默认端口号
    
        /**
         * 发送邮件,验证用户权限
         * 
         * @param smtpHost       邮箱服务器
         * @param mailServerPort 邮箱服务器端口
         * @param mailFrom       发送方邮箱地址
         * @param toList         收件方邮箱集合
         * @param ccList         抄送邮箱地址集合
         * @param bbList         密送邮箱地址集合
         * @param subJect        邮件主题
         * @param messageStr     邮件内容
         * @param fileList       附件路径集合
         * @return
         * @throws UnsupportedEncodingException
         */
        public int authSend(String userName, String password, String smtpHost, String serverPort, String mailFrom,
                Vector<String> toList, Vector<String> ccList, Vector<String> bccList, String subJect, String messageContent, Vector fileList)
                throws UnsupportedEncodingException {
            // 获取系统属性
            Properties properties = System.getProperties();
    
            // 设置邮件服务器
            properties.setProperty("mail.smtp.host", smtpHost);
            // 设置端口
            properties.setProperty("mail.smtp.port", mailServerPort);
            // 设置邮箱是否需要验证
            properties.setProperty("mail.smtp.auth", "true");
    
            // 获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName, password); // qq邮箱用户名 密码(qq为授权码) --用于登录邮箱服务器的用户名密码
                }
            });
    
            session.setDebug(false); // 是否开启debug模式,用于调试
            try {
                // 创建默认的 MimeMessage 对象
                MimeMessage message = new MimeMessage(session);
    
                // Set From: 头部头字段
                message.setFrom(new InternetAddress(mailFrom, "nickName")); // 发件人名称可以不设置
    
                InternetAddress[] addArr = null;
                // 设置收件人
                addArr = new InternetAddress[toList.size()];
                for (int i = 0; i < toList.size(); i++) {
                    String mailtoString = (String) toList.get(i);
                    addArr[i] = new InternetAddress(mailtoString);
                }
                message.setRecipients(Message.RecipientType.TO, addArr); // 设置收件人地址
    
                // 设置抄送人地址
                if ((ccList != null) && (ccList.size() != 0)) {
                    addArr = new InternetAddress[ccList.size()];
                    for (int i = 0; i < ccList.size(); i++) {
                        String ccMailStr = (String) ccList.get(i);
                        addArr[i] = new InternetAddress(ccMailStr);
                    }
                    message.setRecipients(Message.RecipientType.CC, addArr); // 设置抄送人地址
                }
    
                // 设置密送人地址
                if ((bccList != null) && (bccList.size() != 0)) {
                    addArr = new InternetAddress[bccList.size()];
                    for (int i = 0; i < bccList.size(); i++) {
                        String bccMailStr = (String) bccList.get(i);
                        addArr[i] = new InternetAddress(bccMailStr);
                    }
                    message.setRecipients(Message.RecipientType.BCC, addArr); // 设置密送人地址
                }
                // Set Subject: 头部头字段
                message.setSubject(subJect);
                if ((fileList == null) || (fileList.size() == 0)) { // 没有附件
                    // 设置消息体
                    message.setText(messageContent);
                } else {
                    // 带有附件的邮件发送
                    MimeMultipart multi = new MimeMultipart();
                    BodyPart bodyPartText = new MimeBodyPart();
                    bodyPartText.setText(messageContent); // 设置邮件内容
                    multi.addBodyPart(bodyPartText);
                    String fileName = null;
                    for (int i = 0; i < fileList.size(); i++) {
                        fileName = (String) fileList.get(i);
                        FileDataSource fds = new FileDataSource(fileName);
                        
                        BodyPart fileBodyPart = new MimeBodyPart();
                        fileBodyPart.setDataHandler(new DataHandler(fds));  // 设置附件文件数据
                        
                        fileBodyPart.setFileName(fds.getName()); // 设置附件文件名称
                        multi.addBodyPart(fileBodyPart);
                    }
                    message.setContent(multi);
                    
                }
    
                message.setSentDate(new Date()); // 邮件邮件发送时间
                message.saveChanges();
                
                long btime = System.currentTimeMillis();
                // 发送消息
                Transport.send(message);
                
                long etime = System.currentTimeMillis();
                
                String sendmessage = "发件人:"+mailFrom+"发送成功\n收件人:"+toList+"\n";
                if (ccList != null && ccList.size() != 0) {
                    sendmessage += "抄送人:"+ccList+"\n";
                }
                if (bccList != null && bccList.size() != 0) {
                    sendmessage += "密送人:"+bccList+"\n";
                }
                sendmessage += "用时:"+(etime - btime)+"ms";
                System.out.println("Sent message successfully....\n"+sendmessage);
            } catch (MessagingException mex) {
                mex.printStackTrace();
                return 1;
            }
            return 0;
        }
    
        public void setMailServerPort(String mailServerPort) {
            this.mailServerPort = mailServerPort;
        }
    }
    

    测试类

    
    import java.io.UnsupportedEncodingException;
    import java.util.Vector;
    
    import mail.service.SendEmailService;
    
    /**
     * 发送邮件测试
     * 
     * @author lxh96
     *
     */
    public class SendEmail {
        public static void main(String[] args) {
            SendEmailService sendEmail = new SendEmailService();
            String userName = "34**9@qq.com";
            String password = "QQ邮箱授权码或者其他登陆邮箱密码";
            String smtpHost = "smtp.qq.com";
            String serverPort = "465";
            String mailFrom = "34**9@qq.com";
            Vector<String> toList = new Vector<String>() ;
            toList.addElement("*****4@163.com");
            toList.addElement("56***7@qq.com");
            Vector<String> ccList = new Vector<String>();
            ccList.addElement("56**7@qq.com");
            Vector<String> bccList = new Vector<String>();
            bccList.addElement("*****@163.com");
            String subJect = "hello 测试";
            String messageContent = "hello ,我是一个javamail的测试邮件";
            Vector<String> fileList = new Vector<String>();
            fileList.addElement("C:\\Users\\lxh96\\Pictures\\B01.jpg");
            fileList.addElement("C:\\Users\\lxh96\\Pictures\\unnamed.jpg");
            try {
                sendEmail.authSend(userName, password, smtpHost, serverPort, mailFrom, toList, ccList, bccList, subJect,
                        messageContent, fileList);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("邮件发送失败");
            }
        }
    }
    

    能够实现简单邮件多人发送、多人抄送、密送和多附件的发送功能。可能需要根据不同的邮件发送服务器修改或添加相应的properties配置,但应该大同小异。

    相关文章

      网友评论

        本文标题:javaMail发送qq邮件(二):可发送抄送密送多人,支持附件

        本文链接:https://www.haomeiwen.com/subject/urehuhtx.html