zoukankan      html  css  js  c++  java
  • Java程序发送邮件的两种方法

    前一段时间我在博客中发表过Java接收解析邮件的程序,今天,我来总结两种发送邮件的程序。
    下是两种邮件发送方式。
    给出的例子是是发送HTML格式带附件的邮件。(普通文本格式的邮件基本上可以不关心,现在的邮件都是HTML格式的!)
    如果不要发送附件,只要发送单纯的HTML邮件。只要把附件部分去掉即可

    很简单,不解释,拿过去直接可以用,好,直接上代码:

    方法一:
    Java代码 复制代码 收藏代码
    1. # **    
    2. # *用spring mail 发送邮件,依赖jar:spring.jar,activation.jar,mail.jar     
    3. # */     
    4. #      
    5. public static void sendFileMail() throws MessagingException {     
    6. #         JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();     
    7. #      
    8. #         // 设定mail server     
    9. #         senderImpl.setHost("smtp.126.com");     
    10. #         senderImpl.setUsername("yuhan0");     
    11. #         senderImpl.setPassword("******");     
    12. #         // 建立HTML邮件消息     
    13. #         MimeMessage mailMessage = senderImpl.createMimeMessage();     
    14. #         // true表示开始附件模式     
    15. #         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true"utf-8");     
    16. #      
    17. #         // 设置收件人,寄件人     
    18. #         messageHelper.setTo("slimes@126.com");     
    19. #         messageHelper.setFrom("yuhan0@126.com");     
    20. #         messageHelper.setSubject("测试邮件!");     
    21. #         // true 表示启动HTML格式的邮件     
    22. #         messageHelper.setText("<html><head></head><body><h1>你好:附件!!</h1></body></html>"true);     
    23. #      
    24. #         FileSystemResource file1 = new FileSystemResource(new File("d:/logo.jpg"));     
    25. #         FileSystemResource file2 = new FileSystemResource(new File("d:/读书.txt"));     
    26. #         // 添加2个附件     
    27. #         messageHelper.addAttachment("logo.jpg", file1);     
    28. #              
    29. #         try {     
    30. #             //附件名有中文可能出现乱码     
    31. #             messageHelper.addAttachment(MimeUtility.encodeWord("读书.txt"), file2);     
    32. #         } catch (UnsupportedEncodingException e) {     
    33. #             e.printStackTrace();     
    34. #             throw new MessagingException();     
    35. #         }     
    36. #         // 发送邮件     
    37. #         senderImpl.send(mailMessage);     
    38. #         System.out.println("邮件发送成功.....");     
    39. #      
    40. #     }    

  • 相关阅读:
    The Future of Middleware and the BizTalk Roadmap
    FW: How to spawn a process that runs under the context of the impersonated user in Microsoft ASP.NET pages
    Strips illegal Xml characters
    luogu P2280 激光炸弹(二维前缀和)
    luogu P2704 炮兵阵地(经典状态压缩DP)
    SP1716 GSS3 Can you answer these queries III (线段树维护最大连续子段和)
    二分图判定、匹配问题
    C++语法综合 | 基于char*设计一个字符串类MyString
    luogu P1044 火车进出栈问题(Catalan数)
    C++设计模式 | 三种设计模式基础
  • 原文地址:https://www.cnblogs.com/bjanzhuo/p/3576046.html
Copyright © 2011-2022 走看看