前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java实现阿里企业邮箱以及谷歌邮箱邮件的发送

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

作者头像
故久
发布2020-04-24 16:45:04
2.1K0
发布2020-04-24 16:45:04
举报
文章被收录于专栏:故久故久

一、配置

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

smtpServer=smtp.amuxia.com

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

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

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

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

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
    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 要能够访问需要使用v**、或者工具。

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

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

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯企业邮
腾讯企业邮(Tencent Exmail)是腾讯基于多年海量用户邮件系统研发和运营经验,为企业量身订造的一套办公用邮箱系统。稳定、简洁和快速,整合了丰富的企业应用,涵盖资源共享、消息发布、组织管理等方面。腾讯企业邮和微信生态深度整合,为您提供便捷高效的移动邮件解决方案。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档