javaWeb邮件发送

目录

简单发送原理:

详细原理:

需要导入的Maven依赖:

进行简单邮件发送

 进行图片邮件发送

 网易云邮件发送

邮件接口及其QQ邮件包装类


简单发送原理:

详细原理:

  1. 张三给李四发送邮件通过首先通过网络传输到自己发送的服务器(网易服务器)里.
  2. 服务器(网易服务器)在进行发送的邮箱后缀名判断确认要发送到那个服务器里(QQ服务器).
  3. 在通过SMTP协议发送到对应服务器的POP3里进行接收.
  4. 最后接收的服务器(QQ服务器)进行确认,确认成功,则传输到对应用户的邮箱里. 

需要导入的Maven依赖:

        <!-- 邮件发送依赖 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>

进行简单邮件发送

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class Test02 {
    //发送一封简单的邮件
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");//设置qq邮箱服务器
        properties.setProperty("mail.transport.protocol","smtp");//邮箱发送协议
        properties.setProperty("mail.smtp.auth","true");//设置需要验证用户名密码

        //使用javaMail发送邮箱的五个步骤
        //========== 1.创建定义整个应用程序所需的环境信息Session对象 ==========
        //这个只有QQ才有
        Session defaultInstance = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发送人邮件用户名,授权码
                return new PasswordAuthentication("3068384097@qq.com","sclwoortwaqrddeh");
            }
        });
        //开启Session的debug模式,这样可以看到程序发送Email的状态
        defaultInstance.setDebug(true);

        //========== 2.通过Session对象得到transport对象 ==========
        //从session获取transport对象
        Transport transport = defaultInstance.getTransport();

        //========== 3.使用邮箱的用户名和授权码连上邮件服务器 ==========
        //链接的邮箱,链接的用户,链接的授权码
        transport.connect("smtp.qq.com","3068384097@qq.com","sclwoortwaqrddeh");

        //========== 4.创建邮箱 ==========
        //写邮件
        MimeMessage mimeMessage = new MimeMessage(defaultInstance);//需要传递Session
        mimeMessage.setSubject("Hello");//邮件主题
        mimeMessage.setFrom(new InternetAddress("3068384097@qq.com"));//设置发件人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("3068384097@qq.com"));//收件人
        mimeMessage.setText("Hello World");//邮件内容,格式

        //========== 5.发送邮件 ==========
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        transport.close();
    }
}

 进行图片邮件发送

 比起纯文本邮件,图片邮件,只需要改动发送的地方就可以了!

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class Test02 {
    //发送带有图片和附件的邮件
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");//设置qq邮箱服务器
        properties.setProperty("mail.transport.protocol", "smtp");//邮箱发送协议
        properties.setProperty("mail.smtp.auth", "true");//设置需要验证用户名密码

        //使用javaMail发送邮箱的五个步骤
        //========== 1.创建定义整个应用程序所需的环境信息Session对象 ==========
        //这个只有QQ才有
        Session defaultInstance = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发送人邮件用户名,授权码
                return new PasswordAuthentication("3068384097@qq.com", "sclwoortwaqrddeh");
            }
        });
        //开启Session的debug模式,这样可以看到程序发送Email的状态
        defaultInstance.setDebug(true);

        //========== 2.通过Session对象得到transport对象 ==========
        //从session获取transport对象
        Transport transport = defaultInstance.getTransport();

        //========== 3.使用邮箱的用户名和授权码连上邮件服务器 ==========
        //链接的邮箱,链接的用户,链接的授权码
        transport.connect("smtp.qq.com", "3068384097@qq.com", "sclwoortwaqrddeh");

        //========== 4.创建邮箱 ==========
        //写邮件
        MimeMessage mimeMessage = new MimeMessage(defaultInstance);//需要传递Session
        mimeMessage.setFrom(new InternetAddress("3068384097@qq.com"));//设置发件人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("3068384097@qq.com"));//收件人
        mimeMessage.setSubject("Hello");//邮件主题

        //------- 准备图片数据 -----------
        //准备图片数据
        MimeBodyPart img = new MimeBodyPart();

        //图片需要经过数据处理
        DataHandler dataHandler = new DataHandler(new FileDataSource("C:\\Users\\Administrator\\Pictures\\小步.png"));
        img.setDataHandler(dataHandler);
        img.setContentID("bz.jpg");
        //准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<img src='cid:bz.jpg'>", "text/html;charset=UTF-8");
        //描述正文关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(img);
        mm.setSubType("related");
        //-------------
        mimeMessage.setContent(mm);//将编译好的图片放入
        mimeMessage.saveChanges();//保存修改
        //========== 5.发送邮件 ==========
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    }
}

 网易云邮件发送

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

//网易云邮箱发送
public class Test03 {
    public static void main(String[] args) throws MessagingException {
        //网易云邮箱发送
        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.163.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        //1.新建一个会话
        Session session = Session.getInstance(props);

        //2.新建消息
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("abc306384097@163.com"));//设置是谁发送的
        //设置邮件内容
        msg.setSubject("Hello world");
        msg.setText("Hello world");

        //3.建立邮箱链接
        Transport transport = session.getTransport();
        transport.connect("smtp.163.com","abc306384097@163.com","TWENQQAQWAIBVAGF");
        //4.发送消息
        transport.sendMessage(msg,new Address[]{new InternetAddress("abc306384097@163.com")});
        transport.close();
    }
}

邮件接口及其QQ邮件包装类

 接口:

package com.util.Mail;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;

/**
 * 该接口用于实现发送邮件
 */
public interface Mail{
    //获取会话
    Session getSession();
    //获取建立的链接邮箱
    Transport getTransport();
    //获取发送的消息
    Message getMessage();
}

包装类:

package com.util.Mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * 该类用于进行QQ邮箱的发送消息
 */
public class QQMail implements Mail {
    //发送者
    private String sender;
    //接收者
    private String recipient;
    //授权码
    private String AuthorizationCode;
    //会话
    private Session session;
    //邮箱链接
    private Transport transport;
    //发送的消息
    private Message message;
    //附件信息
    private final MimeMultipart mimeMultipart = new MimeMultipart();

    public QQMail() {
        InformationInitialization();
    }

    /**
     * QQMail的构造方法用来设置参数并初始化信息
     *
     * @param sender            设置发件人
     * @param recipient         设置收件人
     * @param authorizationCode 设置授权码
     */
    public QQMail(String sender, String recipient, String authorizationCode) {
        this.sender = sender;
        this.recipient = recipient;
        AuthorizationCode = authorizationCode;
        InformationInitialization();
    }

    /**
     * 该方法用来初始化属性
     */
    private void InformationInitialization() {
        if (sender == null || recipient == null || AuthorizationCode == null) {
            System.err.println("接收者或发送者或授权码参数不能为空!!!!");
        }
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");//设置qq邮箱服务器
        properties.setProperty("mail.transport.protocol", "smtp");//邮箱发送协议
        properties.setProperty("mail.smtp.auth", "true");//设置需要验证用户名密码
        session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发送人邮件用户名,授权码
                return new PasswordAuthentication(sender, AuthorizationCode);
            }
        });
        try {
            transport = session.getTransport();
        } catch (NoSuchProviderException e) {
            System.err.println("QQMail类的InformationInitialization()方法transport邮箱链接初始化有误!");
        }
        try {
            transport.connect("smtp.qq.com", sender, AuthorizationCode);
        } catch (MessagingException e) {
            System.err.println("QQMail类的InformationInitialization()方法transport服务器链接有误!");
        }
        message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(sender));//设置发件人
            message.setRecipient(Message.RecipientType.BCC, new InternetAddress(recipient));//收件人
        } catch (MessagingException e) {
            System.err.println("QQMail类的InformationInitialization()方法message设置有误!");
        }

        try {
            mimeMultipart.setSubType("mixed");
        } catch (MessagingException e) {
            System.err.println("QQMail类的InformationInitialization()方法mimeMultipart类型设置有误!");
        }
    }

    /**
     * 该方法用来设置发送邮件标题
     * @param Title 邮件标题
     */
    public void setMessageTitle(String Title) {
        try {
            message.setSubject(Title);
        } catch (MessagingException e) {
            System.err.println("QQMail类的setMessageTitle()方法标题设置有误!");
        }
    }

    /**
     * 邮件文本添加
     * @param Text 需要进行添加的文本
     * @throws MessagingException   可能会文本添加失败
     */
    public void messageAddText(String Text) throws MessagingException {
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(Text, "text/html;charset=UTF-8");
        mimeMultipart.addBodyPart(mimeBodyPart);
    }

    /**
     * 该方法用于向邮件添加图片
     * @param url 需要添加图片的地址
     */
    public void messageAddImg(String url) throws MessagingException {
        MimeBodyPart img = new MimeBodyPart();
        DataHandler dataHandler = new DataHandler(new FileDataSource(url));
        img.setDataHandler(dataHandler);
        img.setContentID("img.jpg");
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<img src='cid:img.jpg'>", "text/html;charset=UTF-8");
        mimeMultipart.addBodyPart(img);
        mimeMultipart.addBodyPart(text);
    }

    /**
     * 该方法用于向邮件添加附件
     * @param url  需要添加附件的地址
     */
    public void messageAddEnclosure(String url) throws MessagingException {
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setDataHandler(new DataHandler(new FileDataSource(url)));
        String name=url.substring(url.lastIndexOf("\\")+1);
        mimeBodyPart.setFileName(name);
        mimeMultipart.addBodyPart(mimeBodyPart);
    }

    /**
     * 该方法用来设置是否开启检测功能
     * @param debug 设置是否开启
     */
    public void setDebug(Boolean debug){
        session.setDebug(debug);
    }

    /**
     * 该方法用来实现发送邮件
     *
     * @throws MessagingException 可能关闭失败
     */
    public void sendMail() throws MessagingException {
        message.setContent(mimeMultipart);
        message.saveChanges();
        try {
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            System.err.println("\"QQMail类的sendMail()方法发送异常!");
        }
        transport.close();
        System.gc();
    }

    /**
     * 获取邮箱会话
     *
     * @return 返回邮箱会话
     */
    @Override
    public Session getSession() {
        return session;
    }

    /**
     * 获取建立端口的链接
     *
     * @return 返回链接
     */
    @Override
    public Transport getTransport() {
        return transport;
    }

    /**
     * 获取发送消息
     *
     * @return 返回发送消息
     */
    @Override
    public Message getMessage() {
        return message;
    }

    /**
     * 获取发送者
     *
     * @return 返回发送者信息
     */
    public String getSender() {
        return sender;
    }

    /**
     * 设置发送者
     *
     * @param sender 设置发送者信息
     */
    public void setSender(String sender) {
        this.sender = sender;
        InformationInitialization();
    }

    /**
     * 获取接收者
     *
     * @return 返回接收者信息(邮箱)
     */
    public String getRecipient() {
        return recipient;
    }

    /**
     * 设置接收者
     *
     * @param recipient 设置接收者信息
     */
    public void setRecipient(String recipient) {
        this.recipient = recipient;
        InformationInitialization();
    }


    /**
     * 获取授权码
     *
     * @return 返回授权码信息
     */
    public String getAuthorizationCode() {
        return AuthorizationCode;
    }

    /**
     * 设置授权码
     *
     * @param authorizationCode 设置授权码信息
     */
    public void setAuthorizationCode(String authorizationCode) {
        AuthorizationCode = authorizationCode;
        InformationInitialization();
    }
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

123小步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值