java实现阿里企业邮箱以及谷歌邮箱邮件的发送

原创
2020/03/26 16:33
阅读数 542

一、配置

在Syn.properties进行邮箱host等配置

smtpServer=smtp.amuxia.com

fromUserName=邮箱的用户名
fromUserPassword=你的密码

#注意如果是企业邮箱需要smtp.企业的域名 比如我的域名是amuxia.com(当然这个也是假的,举个例子,哈哈)

如果是个人邮箱就是 smtpServer=smtp.aliyun.com

如果是企业邮箱不用域名的话,运行就会报错


 

二、设置取读配置文件的类EmailInfo

public class EmailInfo {
    private String smtpServer; 
    // SMTP服务器地址
    private String port; // 端口
    private String username; 
    // 登录SMTP服务器的用户名,发送人邮箱地址
    private String password; 
    // 登录SMTP服务器的密码
    public EmailInfo() {
        String path=this.getClass().getClassLoader().getResource(".").getPath()+"Syn.properties";
        ConfigurationFile config = new ConfigurationFile(path);
        this.smtpServer = config.getValue("smtpServer");
        //this.port = config.getValue("port");
        this.username = config.getValue("fromUserName");
        this.password = config.getValue("fromUserPassword"); 
    }
    

    
    public String getSmtpServer() {
        return smtpServer;
    }

    public void setSmtpServer(String smtpServer) {
        this.smtpServer = smtpServer;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

三、编写发送邮件的工具类 EmailUtil

public class EmailUtil {
    
    private static  Logger  log = Logger.getLogger(EmailUtil.class);
    
    
     public void send(String to[], String cs[], String ms[], String subject,
                    String content, String fileList[]) {
                try {
                    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
                    Properties p = new Properties();
                    EmailInfo info=new EmailInfo();
                    p.put("mail.debug", "true");
                    p.put("mail.smtp.host", info.getSmtpServer());
                    p.put("mail.smtp.ssl.enable", "true");
                    p.put("mail.smtp.socketFactory.class", SSL_FACTORY);
                    p.put("mail.smtp.port", "465");
                    p.put("mail.smtp.socketFactory.port", "465");
                    // props.put("mail.smtp.socketFactory.fallback", "false");
                    p.put("mail.smtp.auth", "true");
                    // 建立会话
                   // Session session = Session.getInstance(p);
                    Session session = Session.getDefaultInstance(p,
                            new Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(info.getUsername(), info.getPassword());
                            }
                            });
                    Message msg = new MimeMessage(session); // 建立信息
                    BodyPart messageBodyPart = new MimeBodyPart();
                    Multipart multipart = new MimeMultipart();
                    msg.setFrom(new InternetAddress(info.getUsername())); // 发件人

                    String toList = null;
                    String toListcs = null;
                    String toListms = null;

                    // 发送,
                    if (to != null) {
                        toList = getMailList(to);
                        InternetAddress[] iaToList = new InternetAddress()
                                .parse(toList);
                        msg.setRecipients(Message.RecipientType.TO, iaToList); // 收件人
                    }

                    // 抄送
                    if (cs != null) {
                        toListcs = getMailList(cs);
                        InternetAddress[] iaToListcs = new InternetAddress()
                                .parse(toListcs);
                        msg.setRecipients(Message.RecipientType.CC, iaToListcs); // 抄送人
                    }

                    // 密送
                    if (ms != null) {
                        toListms = getMailList(ms);
                        InternetAddress[] iaToListms = new InternetAddress()
                                .parse(toListms);
                        msg.setRecipients(Message.RecipientType.BCC, iaToListms); // 密送人
                    }
                    msg.setSentDate(new Date()); // 发送日期
                    msg.setSubject(subject); // 主题
                    msg.setText(content); // 内容
                    // 显示以html格式的文本内容
                    messageBodyPart.setContent(content, "text/html;charset=gbk");
                    multipart.addBodyPart(messageBodyPart);

                    // 2.保存多个附件
                    if (fileList != null) {
                        addTach(fileList, multipart);
                    }

                    msg.setContent(multipart);
                    // 邮件服务器进行验证
                    Transport tran = session.getTransport("smtp");
                    tran.connect(info.getSmtpServer(), info.getUsername(),info.getPassword());
                    tran.sendMessage(msg, msg.getAllRecipients()); // 发送
                   //Transport.send(msg);
                    System.out.println("邮件发送成功");
                    log.info("邮件发送成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("邮件发送失败:"+e);
                }
            }

     
     private String getMailList(String[] mailArray) {

            StringBuffer toList = new StringBuffer();
            int length = mailArray.length;
            if (mailArray != null && length < 2) {
                toList.append(mailArray[0]);
            } else {
                for (int i = 0; i < length; i++) {
                    toList.append(mailArray[i]);
                    if (i != (length - 1)) {
                        toList.append(",");
                    }

                }
            }
            return toList.toString();

        }
     
     
        // 添加多个附件
        public void addTach(String fileList[], Multipart multipart)
                throws MessagingException, UnsupportedEncodingException {
            for (int index = 0; index < fileList.length; index++) {
                MimeBodyPart mailArchieve = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(fileList[index]);
                mailArchieve.setDataHandler(new DataHandler(fds));
                mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),
                        "GBK", "B"));
                multipart.addBodyPart(mailArchieve);
            }
        }
    }

四、最后在进行test

    public static void main(String[] args) {

       EmailUtil send =new EmailUtil();

       //发送给谁
        String to[] = { "xxx@qq.com","xxxx@163.com" };

        String cs[] = { "xxxx@qq.com" };   //抄送
        String ms[] = null;//密送
        String subject = "测试一下";
        String content = "这是邮件内容,仅仅是测试,不需要回复";
        String[] arrArchievList = new String[2];
        arrArchievList[0] = "C:\\Users\\pc\\Pictures\\Camera Roll\\photo-1551334787-21e6bd3ab135.jpg";
        arrArchievList[1] = "C:\\Users\\pc\\Pictures\\Camera Roll\\timg.jpg";
       // arrArchievList[2] = "D:\\demo.rar";
        // 2.保存多个附件
        send.send(to, cs, ms, subject, content,arrArchievList);

}

五、谷歌发送邮箱

国内已封gmail的ip 要能够访问需要使用vpn、或者翻墙工具。

在使用gmail邮箱发送邮件之前需要先开启相关的配置项

谷歌邮件发送只需将Syn.properties的几个参数修改下,其它代码跟以上的还是一样的。

smtpServer=smtp.gmail.com //谷歌邮箱的域名 这里是我的个人谷歌邮箱 公司的话需要使用公司的域名
fromUserName=zxxxxxx@gmail.com 我的谷歌邮箱的用户名
fromUserPassword=xxxxxxx  邮箱的密码

以上就是邮箱发送的一些注意事项与代码。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部