Java实现简单邮件发送功能

 更新时间:2022年06月22日 11:02:14   作者:深蓝梦夕阳  
这篇文章主要为大家详细介绍了Java实现简单邮件发送功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Java实现简单邮件发送的具体代码,供大家参考,具体内容如下

需要的jar包:

  • activation-1.1.1.jar
  • mail-1.4.7.jar

QQ邮箱设置开启POP3/SMTP服务,并获得授权码

java实现简单邮件发送

import com.sun.mail.util.MailSSLSocketFactory;

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

public class Mail1 {
    public static  void main(String[] args) throws Exception {
        //要发送邮件,需要获得协议和支持!开启服务POP3/SMTP服务  授权码: fsxqgovorymigfeb
        Properties prop=new Properties();
        prop.setProperty("mail.host","smtp.qq.com");//设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");//设置邮箱发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码

        //QQ邮箱还有设置SSL加密
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);

        //1.创建定义整个应用程序所需要的环境信息的Session对象
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1369410772@qq.com","fsxqgovorymigfeb");
            }
        });

        //开启session的debug模式,这样就可以查看运行状态了
        session.setDebug(true);

        //2.通过session对象获得transport对象
        Transport transport = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        transport.connect("smtp.qq.com","1369410772@qq.com","fsxqgovorymigfeb");
        //4.创建邮件:写邮件
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress("1369410772@qq.com"));//发件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("1369410772@qq.com"));//收件人
        message.setSubject("你好");//邮件主题
        message.setContent("<h1 style='color: red'>你好</h1>","text/html;charset=utf-8");//邮件内容
        //5.发送邮件
        transport.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        transport.close();

    }
}

java实现复杂邮件发送( 带文件 )

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.util.Properties;

public class Mail1 {
    public static  void main(String[] args) throws Exception {
        //要发送邮件,需要获得协议和支持!开启服务POP3/SMTP服务  授权码: fsxqgovorymigfeb
        Properties prop=new Properties();
        prop.setProperty("mail.host","smtp.qq.com");//设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");//设置邮箱发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码

        //QQ邮箱还有设置SSL加密
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);

        //1.创建定义整个应用程序所需要的环境信息的Session对象
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1369410772@qq.com","fsxqgovorymigfeb");
            }
        });

        //开启session的debug模式,这样就可以查看运行状态了
        session.setDebug(true);

        //2.通过session对象获得transport对象
        Transport transport = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        transport.connect("smtp.qq.com","1369410772@qq.com","fsxqgovorymigfeb");
        //4.创建邮件:写邮件
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress("1369410772@qq.com"));//发件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("1369410772@qq.com"));//收件人
        message.setSubject("你好");//邮件主题
        //message.setContent("<h1 style='color: red'>你好</h1>","text/html;charset=utf-8");//邮件内容

        //=============================================================================
        //带图片的内容
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("E:\\IDEA\\JavaWeb\\mail-java\\src\\tx.png"));//图片需要经过数据处理... DataHandler:数据处理
        image.setDataHandler(dh);//在Body中放入处理的图片数据
        image.setContentID("tx.png");//给图片设置ID

        //准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封邮件正文带图片<img src='cid:tx.png'>的邮件","text/html;charset=utf-8");

        //描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("mixed");

        //设置到消息中,保存修改
        message.setContent(mm);
        message.saveChanges();
        //=========================================================================

        //5.发送邮件
        transport.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        transport.close();

    }
}

Spring实现

1、添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、编写配置文件

spring.mail.username=1369410772@qq.com
spring.mail.password=fsxqgovorymigfeb
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true

3、编写测试类

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class DemoApplicationTests {//简单邮件

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        //发送邮件
        //收件人
        //内容

        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("测试");
        message.setText("Hello");
        message.setFrom("1369410772@qq.com");
        message.setTo("1369410772@qq.com");
        mailSender.send(message);

    }

    @Test
    public void test2() throws Exception {//复杂邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("测试");
        helper.setText("Hello",true);

        //附件
        helper.addAttachment("1.jpg",new File(""));

        helper.setFrom("1369410772@qq.com");
        helper.setTo("1369410772@qq.com");

        mailSender.send(mimeMessage);

    }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot封装响应数据实现过程详解

    SpringBoot封装响应数据实现过程详解

    这篇文章主要介绍了SpringBoot封装响应数据实现过程,SpringBoot响应数据封装是指在SpringBoot应用程序中,将返回的数据进行封装,以便于前端页面或其他客户端使用,感兴趣想要详细了解可以参考下文
    2023-05-05
  • Mysql中备份表的多种方法

    Mysql中备份表的多种方法

    本文给大家分享Mysql中备份表的四种方法,第一种方式是小表的备份,第二种是对整个数据库的备份与恢复,第三种是对某个数据表进行备份,每种方式给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2022-11-11
  • java常用工具类 UUID、Map工具类

    java常用工具类 UUID、Map工具类

    这篇文章主要为大家详细介绍了Java常用工具类,包括UUID工具类、Map工具类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-05-05
  • SpringBoot RESTful风格入门讲解

    SpringBoot RESTful风格入门讲解

    RESTful是一种web软件风格,它不是标准也不是协议,它不一定要采用,只是一种风格,它倡导的是一个资源定位(url)及资源操作的风格,这篇文章主要介绍了SpringBoot使用RESTful接口
    2022-11-11
  • java经典问题:连个字符串互为回环变位

    java经典问题:连个字符串互为回环变位

    连个字符串互为回环变位经常出现在java程序员面试中,这个是考验程序员的解题思路和方法的最经典的一题,小编为大家详细分析一下,一起来学习吧。
    2017-11-11
  • Java8中Function接口的使用方法详解

    Java8中Function接口的使用方法详解

    在 Java 8 中,Function 接口是 java.util.function 包中的一个函数式接口,函数式接口是仅包含一个抽象方法的接口,适用于 Lambda 表达式或方法引用,本文给大家介绍了Java8的Function接口的使用方法,需要的朋友可以参考下
    2024-09-09
  • spring mybatis环境常量与枚举转换示例详解

    spring mybatis环境常量与枚举转换示例详解

    这篇文章主要为大家介绍了spring mybatis环境常量与枚举转换示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • JAVA面试题 简谈你对synchronized关键字的理解

    JAVA面试题 简谈你对synchronized关键字的理解

    这篇文章主要介绍了JAVA面试题 请谈谈你对Sychronized关键字的理解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • macOS上使用gperftools定位Java内存泄漏问题及解决方案

    macOS上使用gperftools定位Java内存泄漏问题及解决方案

    这篇文章主要介绍了macOS上使用gperftools定位Java内存泄漏问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • 关于Idea卡在Resolving Maven dependencies的解决方案

    关于Idea卡在Resolving Maven dependencies的解决方案

    本文详细介绍了关于Idea卡在Resolving Maven dependencies的解决方案,文中通过图文结合的形式给大家介绍的非常详细,对大家解决问题有一定的帮助,需要的朋友可以参考下
    2024-02-02

最新评论