zoukankan      html  css  js  c++  java
  • java实现邮件发送

    介绍

    发送邮件是一个很常见的需求,如用户注册,用户密码修改,密码找回等。今天我们看一下使用JavaSE和Spring实现发送邮件的功能。

    邮件协议

    SMTP协议是基于TCP/IP的一个应用层协议,类似于HTTP,全称为 Simple Mail Transfer Protocol,译作简单邮件传输协议,它定义了邮件客户端软件与SMTP 服务器之间,以及 SMTP 服务器与 SMTP 服务器之间的通信规则。我们通过邮件客户端或程序发送邮件时就用到了该协议。
    而 POP3 协议全称为 Post Office Protocol ,译作邮局协议,它定义了邮件客户端与 POP3服务器之间的通信规则。我们通过邮件客户端查看邮件时就用到了该协议。
    IMAP(Internet Message Access Protocol)协议是对POP3协议的一种扩展,功能更强,作用类似。

    发送前准备

    发送前需要获取邮箱的授权码,以网易126邮箱为例

    使用JavaSE发送简单邮件

    添加maven依赖

    <dependency>
          <groupId>com.sun.mail</groupId>
          <artifactId>javax.mail</artifactId>
          <version>1.6.2</version>
    </dependency>
    

    发送邮件

    public class Client {
    
      public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        //设置邮件地址
        props.put("mail.smtp.host", "smtp.126.com");
        //开启认证
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, null);
        Transport transport = session.getTransport();
        //用户名
        String user = "xxx@126.com";
        //授权码
        String password = "xxx";
        transport.connect(user, password);
        //创建邮件消息
        MimeMessage msg = new MimeMessage(session);
        msg.setSentDate(new Date());
        //邮件发送人
        InternetAddress fromAddress = new InternetAddress(user, "邮件服务");
        msg.setFrom(fromAddress);
        //邮件接收人
        String to = "xxx@163.com";
        InternetAddress[] toAddress = new InternetAddress[]{new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, toAddress);
        //邮件主题
        msg.setSubject("测试邮件发送", "UTF-8");
        //邮件内容和格式
        msg.setContent("this is a test mail", "text/html;charset=UTF-8");
        msg.saveChanges();
        //发送
        transport.sendMessage(msg, msg.getAllRecipients());
      }
    
    }
    

    发送带附件的邮件

    public class Client {
    
      public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        //设置邮件地址
        props.put("mail.smtp.host", "smtp.126.com");
        //开启认证
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, null);
        Transport transport = session.getTransport();
        //用户名
        String user = "xxx@126.com";
        //授权码
        String password = "xxx";
        transport.connect(user, password);
        //创建邮件消息
        MimeMessage msg = new MimeMessage(session);
        msg.setSentDate(new Date());
        //邮件发送人
        InternetAddress fromAddress = new InternetAddress(user, "邮件服务");
        msg.setFrom(fromAddress);
        //邮件接收人
        String to = "xxx@163.com";
        InternetAddress[] toAddress = new InternetAddress[]{new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, toAddress);
        //邮件主题
        msg.setSubject("测试邮件发送", "UTF-8");
        //内容和附件
        Multipart multipart = new MimeMultipart();
        //内容
        BodyPart contentBodyPart = new MimeBodyPart();
        contentBodyPart.setContent("this also is a test mail", "text/html;charset=UTF-8");
        multipart.addBodyPart(contentBodyPart);
        //附件
        BodyPart fileBody = new MimeBodyPart();
        DataSource source = new FileDataSource("D:/a.png");
        fileBody.setDataHandler(new DataHandler(source));
        fileBody.setFileName("测试附件.png");
        multipart.addBodyPart(fileBody);
        //邮件内容
        msg.setContent(multipart);
        msg.saveChanges();
        //发送
        transport.sendMessage(msg, msg.getAllRecipients());
      }
    
    }
    

    使用Spring发送简单邮件

    spring在原有的基础上又封装了一层,简化了开发。

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>5.1.2.RELEASE</version>
    </dependency>
    <dependency>
          <groupId>com.sun.mail</groupId>
          <artifactId>javax.mail</artifactId>
          <version>1.6.2</version>
    </dependency>
    
    public class Client {
    
      public static void main(String[] args) throws Exception {
        JavaMailSender mailSender = createJavaMailSender();
        //创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        //发送人
        messageHelper.setFrom("xxx@126.com", "邮件服务");
        //收件人
        messageHelper.setTo("xxx@163.com");
        //主题
        messageHelper.setSubject("测试邮件发送");
        //发送时间
        messageHelper.setSentDate(new Date());
        //发送内容
        messageHelper.setText("this is a test mail by spring");
        mailSender.send(mimeMessage);
      }
    
      private static JavaMailSender createJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setDefaultEncoding(StandardCharsets.UTF_8.name());
        String username = "xxx@126.com";
        //设置用户名
        mailSender.setUsername(username);
        //设置授权码
        mailSender.setPassword("xxx");
        Properties props = new Properties();
        //设置邮件地址
        props.put("mail.smtp.host", "smtp.126.com");
        //开启认证
        props.put("mail.smtp.auth", "true");
        mailSender.setJavaMailProperties(props);
        return mailSender;
      }
    }
    

    使用Spring发送带附件的邮件

    public class Client {
    
      public static void main(String[] args) throws Exception {
        JavaMailSender mailSender = createJavaMailSender();
        //创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //multipart为true表示可以带附件
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        //发送人
        messageHelper.setFrom("xxx@126.com", "邮件服务");
        //收件人
        messageHelper.setTo("xxx@163.com");
        //主题
        messageHelper.setSubject("测试邮件发送");
        //发送时间
        messageHelper.setSentDate(new Date());
        //发送内容
        messageHelper.setText("this is a test mail by spring");
        //添加附件
        messageHelper.addAttachment("测试附件.png", new FileDataSource("D:/a.png"));
        mailSender.send(mimeMessage);
      }
    
      private static JavaMailSender createJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setDefaultEncoding(StandardCharsets.UTF_8.name());
        String username = "xxx@126.com";
        //设置用户名
        mailSender.setUsername(username);
        //设置授权码
        mailSender.setPassword("xxx");
        Properties props = new Properties();
        //设置邮件地址
        props.put("mail.smtp.host", "smtp.126.com");
        //开启认证
        props.put("mail.smtp.auth", "true");
        mailSender.setJavaMailProperties(props);
        return mailSender;
      }
    }
    
  • 相关阅读:
    java_IO流之 NIO
    No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer)
    JAVA I/O流 之入门
    10年老司机经验总结--程序员兼职的那些事
    python 去除html 超链接href 如何实现?
    《模式分类(原书第二版)》pdf格式下载电子书免费下载
    通知-招财猫问题通知专用
    Centos6.5 安装 python3.5 虚拟环境 virtualenvwrapper
    5.区块链平台以太坊从入门到精通之 以太网区块链网络
    4.区块链平台以太坊从入门到精通之 以太币
  • 原文地址:https://www.cnblogs.com/strongmore/p/13876058.html
Copyright © 2011-2022 走看看