JavaMail

Posted Vodka~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaMail相关的知识,希望对你有一定的参考价值。

一, 用于处理电子邮件相关的编程接口,javaMail 是由Sun定义的一套收发电子邮件的API,它可以方便地执行一些常用的邮件传输,不同的厂商可以提供自己的实现类,但它并没有包含在jdk中,而是作为javaEE的一部分。

二, 厂商所提供的javamail服务程序可以有选择的实现某些邮件协议,常见的邮件协议:
-SMTP: 简单邮件传输协议,用于发送电子邮件的传输协议
-POP3: 用于接收电子邮件的标准协议。
-IMAP: 互联网消息协议,是POP3的替代协议。
-三种协议都有对应SSL加密传输的协议,分别是 SMTPS, POP3S,和IMAPS 。除JavaMail 服务提供程序之外,JavaMail还需要JAF (JavaBeans Activation Framework) 来处理不是纯文本的邮件内容,包括MIME(多用途互联网邮件扩展),URL 页面和文件附件等内容。另外,JavaMail 依赖 JAF (JavaBeans Activation Framework),JAF 在Java6之后已经合并到JDK中,而JDK5之前需要另外下载JAF的类库。

三,JavaMail 关键对象




四,添加JavaMail相关依赖
在Maven项目中的pom.xml配置文件中添加mail所需的依赖

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

    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>javax.mail-api</artifactId>
      <version>1.6.2</version>
    </dependency>

五,发送普通文本邮件

public class MailTest 
    public static void main(String [] args ) throws  Exception
        //定义邮箱服务器配置
        Properties prop = new Properties ();
        //设置邮件服务器主机名
        prop.setProperty("mail.smtp.host","smtp.163.com");
        //设置邮件服务器端口
        prop.setProperty("mail.smtp.port","25");
        //设置邮件服务器认证属性  (设置为true表示发送服务器需要身份认证)
        prop.setProperty("mail.smtp.auth","true");

        //根据不同的邮箱,决定 SMTP 协议是否需要使用 SSL 安全认证
        prop.setProperty("mail.smtp.port","465");
        prop.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback","false");
        prop.setProperty("mail.smtp.socketFactory.port","465");

        //使用JavaMail发送邮件的五个步骤
        /*
        *   1.创建Session
        *   2.开启Session的 debug 模式,查看到程序发送Email的进程
        *   3.通过Session得到transport对象
        *   4.使用邮箱的用户名和密码连上邮件服务器(用户名只需写 @ 符号前面的内容即可,密码指的是 邮箱协议授权码)
        *
        * */
        Session session = Session.getInstance(prop);
        session.setDebug(true);
        Transport transport = session.getTransport();
        transport.connect("smtp.163.com","lwj18475","PQQVRNRONLXASWQZ");
        Message message= createSimpleMail(session);
        transport.sendMessage(message , message.getAllRecipients());
        transport.close();

    

    public static  Message createSimpleMail(Session session) throws MessagingException 
        /*
        *   1.创建邮件对象
        *   2.设置邮件的发送人
        *   3.设置邮件的接收人
        *   4.设置(邮件的主题,发送时间,邮件内容)
        *   4.返回封装好的邮箱对象
        * */
        MimeMessage message = new MimeMessage(session);
       message.setFrom("lwj18475@163.com");
       message.setRecipients(Message.RecipientType.TO,"lwj18475@163.com");
       message.setSubject("测试文本邮件!");
       message.setSentDate(new Date());
       message.setText("Hello,Vodka!");
       return message;
    

六,发送带附件的邮件

package com.vodka.Test;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
 * @author Vodka
 * @date 2022/02//17:01
 */
public class MailTest 
    public static void main(String [] args ) throws  Exception
        //定义邮箱服务器配置
        Properties prop = new Properties ();
        //设置邮件服务器主机名
        prop.setProperty("mail.smtp.host","smtp.163.com");
        //设置邮件服务器端口
        prop.setProperty("mail.smtp.port","25");
        //设置邮件服务器认证属性  (设置为true表示发送服务器需要身份认证)
        prop.setProperty("mail.smtp.auth","true");

        //根据不同的邮箱,决定 SMTP 协议是否需要使用 SSL 安全认证
        prop.setProperty("mail.smtp.port","465");
        prop.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback","false");
        prop.setProperty("mail.smtp.socketFactory.port","465");

        //使用JavaMail发送邮件的五个步骤
        /*
        *   1.创建Session
        *   2.开启Session的 debug 模式,查看到程序发送Email的进程
        *   3.通过Session得到transport对象
        *   4.使用邮箱的用户名和密码连上邮件服务器(用户名只需写 @ 符号前面的内容即可,密码指的是 邮箱协议授权码)
        *
        * */
        Session session = Session.getInstance(prop);
        session.setDebug(true);
        Transport transport = session.getTransport();
        transport.connect("smtp.163.com","lwj18475","PQQVRNRONLXASWQZ");
        Message message= createAttachMail(session);
        transport.sendMessage(message , message.getAllRecipients());
        transport.close();

    

    public static  Message createAttachMail(Session session) throws MessagingException 
        /*
        *   1.创建邮件对象
        *   2.设置邮件的发送人
        *   3.设置邮件的接收人
        *   4.设置(邮件的主题,发送时间,邮件内容)
        *      Message表示一封邮件的抽象,messages.getContent() 返回一个  Multipart 对象,
        * 一个Multipart包含一个或多个BodyPart对象,来组成邮件的正文部分(包括附件), 将BodyPart嵌入MultiPart,再将MultiPart嵌入Message。
        *   5.返回封装好的邮箱对象
        * */
        MimeMessage message = new MimeMessage(session);
       message.setFrom("lwj18475@163.com");
       message.setRecipients(Message.RecipientType.TO,"lwj18475@163.com");
       message.setSubject("含带附件的邮件!");
       message.setSentDate(new Date());
        //邮件正文
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent("一封带附件的邮件","text/html; charset=utf-8");
        //创建附件
        MimeMultipart mimeMultipart = new MimeMultipart();
        MimeBodyPart attachPart = new MimeBodyPart();
        //获取本地文件
        DataHandler dataHandler = new DataHandler(new FileDataSource("C:\\\\Users\\\\伟神\\\\Desktop\\\\Hotel\\\\VipRoom.jpg"));
        attachPart.setDataHandler(dataHandler);
        //附件名称
        attachPart.setFileName("Spring.Log");
        //添加正文
        mimeMultipart.addBodyPart(bodyPart);
        //添加附件
        mimeMultipart.addBodyPart(attachPart);
        //如果在邮件中添加附件,需要设置为mixed
        mimeMultipart.setSubType("mixed");
        message.setContent(mimeMultipart);
       return message;
    


七,Html内容的邮件

八,


1。邮件信息配置封装类

public class MailConfiguration 
    //服务器信息
    private String Host;
    private String Port;
    //邮件发送者与邮件接收者集合
    private  String FromAddress;
    private List<String> AllRecipients;
    //邮箱的用户名(发送者)
    private String UserName;
    private String UserPwd;
    //邮件认证,主题,内容,附件
    private boolean Authentic = true;
    private String Subject;
    private String Content;
    private List<String> AttachFiles;


    public MailConfiguration() 
    

    public MailConfiguration(String host, String port, String fromAddress, List<String> allRecipients, String userName, String userPwd, boolean authentic, String subject, String content, List<String> attachFiles) 
        Host = host;
        Port = port;
        FromAddress = fromAddress;
        AllRecipients = allRecipients;
        UserName = userName;
        UserPwd = userPwd;
        Authentic = authentic;
        Subject = subject;
        Content = content;
        AttachFiles = attachFiles;
    

    public String getHost() 
        return Host;
    

    public void setHost(String host) 
        Host = host;
    

    public String getPort() 
        return Port;
    

    public void setPort(String port) 
        Port = port;
    

    public String getFromAddress() 
        return FromAddress;
    

    public void setFromAddress(String fromAddress) 
        FromAddress = fromAddress;
    

    public List<String> getAllRecipients() 
        return AllRecipients;
    

    public void setAllRecipients(List<String> allRecipients) 
        AllRecipients = allRecipients;
    

    public String getUserName() 
        return UserName;
    

    public void setUserName(String userName) 
        UserName = userName;
    

    public String getUserPwd() 
        return UserPwd;
    

    public void setUserPwd(String userPwd) 
        UserPwd = userPwd;
    

    public boolean isAuthentic() 
        return Authentic;
    

    public void setAuthentic(boolean authentic) 
        Authentic = authentic;
    

    public String getSubject() 
        return Subject;
    

    public void setSubject(String subject) 
        Subject = subject;
    

    public String getContent() 
        return Content;
    

    public void setContent(String content) 
        Content = content;
    

    public List<String> getAttachFiles() 
        return AttachFiles;
    

    public void setAttachFiles(List<String> attachFiles) 
        AttachFiles = attachFiles;
    

    @Override
    public String toString() 
        return "MailConfiguration" +
                "Host='" + Host + '\\'' +
                ", Port='" + Port + '\\'' +
                ", FromAddress='" + FromAddress + '\\'' +
                ", AllRecipients=" + AllRecipients +
                ", UserName='" + UserName + '\\'' +
                ", UserPwd='" + UserPwd + '\\'' +
                ", Authentic=" + Authentic +
                ", Subject='" + Subject + '\\'' +
                ", Content='" + Content + '\\'' +
                ", AttachFiles=" + AttachFiles +
                '';
    



2.身份认证类
public class MyAuthenticator extends Authenticator 
    private  String UserName;
    private String UserPwd;

    public  MyAuthenticator(String userName , String userPwd)
        this.UserName = userName;
        this.UserPwd = userPwd;
    

    //发送邮件时,进行身份认证
    protected PasswordAuthentication getPasswordAuthentication()
        return new PasswordAuthentication(UserName,UserPwd);
    






3.邮件发送类
public class MailSender 
    public  void sendMail(MailConfiguration mc) throws Exception 
        //定义邮箱服务器配置
        Properties prop = new Properties ();
        //设置邮件服务器主机名
        prop.setProperty("mail.smtp.host",mc.getHost());
        //设置邮件服务器端口
        prop.setProperty("mail.smtp.port",mc.getPort());
        //设置邮件服务器认证属性  (设置为true表示发送服务器需要身份认证)
        prop.setProperty("mail.smtp.auth", String.valueOf(mc.isAuthentic()));
        //身份认证
        MyAuthenticator myAuthenticator = new MyAuthenticator(mc.getUserName(),mc.getUserPwd());

        //创建Session对象
        Session session = Session.getDefaultInstance(prop,myAuthenticator);
        //开启debug模式
        session.setDebug(true);

        //创建Message
        Message message = new MimeMessage(session);
        //设置发送方邮箱地址
        message.setFrom(new InternetAddress(mc.getFromAddress()));
        //设置邮件主题
        message.setSubject(mc.getSubject());
        //设置发送时间
        message.setSentDate(new Date());
        //设置收件地址
        if(mc.getAllRecipients() != null && mc.getAllRecipients().size() > 0)

             Address[] addresses = new Address[mc.getAllRecipients().size()];

             for(int index = 0 ; index < mc.getAllRecipients().size() ; ++index)

                 Address address =  new InternetAddress(mc.getAllRecipients().get(index));

                 addresses[index] = address;

             
             //设置类型,并将接收地址数组添加到message对象
            message.setRecipients(Message.RecipientType.TO,addresses);
        

        //创建多媒体容器
        MimeMultipart mimeMultipart = new MimeMultipart();
        //主体容器
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        以上是关于JavaMail的主要内容,如果未能解决你的问题,请参考以下文章

利用Javamail接收QQ邮箱和Gmail邮箱(转)

JavaMail入门第四篇 接收邮件

JavaMail入门第四篇 接收邮件

javamail接收邮件报错

用javamail接收企业邮箱里的邮件信息的问题

javamail接收邮件(zt)