java发送邮件,不使用springboot

有时候要用到邮件,但是又不是springboot项目,那么就要用到以下方法:

首先要添加maven依赖

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

然后要配置一些参数,我这些参数是放在配置文件中的,然后通过读取配置文件再配置进去,也可以直接写在代码里面,

如下:

#邮件服务器
mail.smtp.host=smtp.qq.com
#发送端口
mail.smtp.port=587
#ֻ只处理SSL的连接,对于非SSL的连接不做处理
mail.smtp.socketFactory.fallback=false
#是要验证用户名和密码
mail.smtp.auth=true
#是否允许使用ssl安全套接字
mail.smtp.ssl.enable=true
#设置发送邮件的账号和密码,是发件人的数据,密码使用秘钥,该秘钥是从邮箱设置那边获取的授权码
mail.user=#######@qq.com
mail.pwd=############
#收件人的邮箱数据
resive.user=#########@qq.com
mail.properties

 

配置文件相应的工具类如下:

 

package send;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

/**
 * 用于处理配置文件的类,判断工程外部是否有配置文件,如果没有,则使用默认的配置文件
 * @author 徐金仁
 */
public class PropertityUtils extends Properties{
    
    private String filePath = null;
    
    public PropertityUtils(String filePath){
        this.filePath = filePath;
        readerFiles();
    }
    
    
    public void readerFiles(){
        File file = new File(filePath);
        InputStream is = null;
        if(file.exists()){
            try {
                is = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            is = this.getClass().getClassLoader().getResourceAsStream(filePath);
        }
        Reader reader = new InputStreamReader(is);
        try {
            this.load(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }    
    public String getValue(String key){
        return this.getProperty(key);
    }
}
PropertityUtils.java

 

接着就是进行邮件发送的配置和封装,如下:

MailUtil.java
package send;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
 * 邮件工具类
 */
public class MailUtil {
    /**
     * 发送邮件
     * @param to 给谁发
     * @param text 发送内容
     */
    private String mail_smtp_host = "";
    private String mail_smtp_port = "";
    private String mail_smtp_socketFactory_fallback = "";
    private String mail_smtp_auth = "";
    private String mail_smtp_ssl_enable = "";
    private String sender = "";
    private String pwd = "";
    private String reciver = "";
    
    public MailUtil(){
        //初始化数据
        PropertityUtils pro = new PropertityUtils("mail.properties");
        this.mail_smtp_host = pro.getValue("mail.smtp.host");
        this.mail_smtp_port = pro.getValue("mail.smtp.port");
        this.mail_smtp_socketFactory_fallback = pro.getValue("mail.smtp.socketFactory.fallback");
        this.mail_smtp_auth = pro.getValue("mail.smtp.auth");
        
        this.mail_smtp_ssl_enable = pro.getValue("mail.smtp.ssl.enable");
        this.mail_smtp_ssl_enable = pro.getValue("mail.user");
        this.pwd = pro.getValue("mail.pwd");
        this.reciver = pro.getValue("resive.user");
        this.sender = pro.getValue("mail.user");
    }
    public  void send_mail(String to,String text) throws MessagingException {
        //创建连接对象 连接到邮件服务器
        Properties properties = new Properties();
        //设置发送邮件的基本参数  
        //发送邮件服务器
        properties.put("mail.smtp.host", "smtp.qq.com");
        //发送端口
        properties.put("mail.smtp.port", "465");
        
        properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理
        properties.put("mail.smtp.auth", "true");       //是要验证用户名和密码
        properties.put("mail.smtp.ssl.enable", true);   //是否允许使用ssl安全套接字
        //设置发送邮件的账号和密码
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //两个参数分别是发送邮件的账户和密码
                return new PasswordAuthentication(sender, pwd);
            }
        });
        //创建邮件对象
        Message message = new MimeMessage(session);
        //设置发件人
        message.setFrom(new InternetAddress(sender));
        //设置收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        //设置主题
        message.setSubject("验证码");
        //设置邮件正文  第二个参数是邮件发送的类型
        message.setContent(text,"text/html;charset=UTF-8");
        //发送一封邮件
        Transport.send(message);
    }
}

测试如下:

package springboot.javaSendEmail;

import javax.mail.MessagingException;

import org.junit.Test;

import send.MailUtil;

/**
 * 测试类
 * @author 徐金仁
 *
 */
public class TestMain {
    @Test    
    public void test1() throws MessagingException{
        MailUtil mailUtil = new MailUtil();
        mailUtil.send_mail("########@qq.com", "你好");
    }
}

 

二:发送带有附件和文本显示图片的邮件

package send;

import javax.activation.DataHandler;
import javax.activation.DataSource;
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 javax.mail.internet.MimePartDataSource;
import javax.mail.internet.MimeUtility;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
/**
 * 邮件工具类
 */
public class MailUtil {
    /**
     * 发送邮件
     * @param to 给谁发
     * @param text 发送内容
     */
    private String mail_smtp_host = "";
    private String mail_smtp_port = "";
    private String mail_smtp_socketFactory_fallback = "";
    private String mail_smtp_auth = "";
    private String mail_smtp_ssl_enable = "";
    private String sender = "";
    private String pwd = "";
    private String reciver = "";
    
    public MailUtil(){
        //初始化数据
        PropertityUtils pro = new PropertityUtils("mail.properties");
        this.mail_smtp_host = pro.getValue("mail.smtp.host");
        this.mail_smtp_port = pro.getValue("mail.smtp.port");
        this.mail_smtp_socketFactory_fallback = pro.getValue("mail.smtp.socketFactory.fallback");
        this.mail_smtp_auth = pro.getValue("mail.smtp.auth");
        
        this.mail_smtp_ssl_enable = pro.getValue("mail.smtp.ssl.enable");
        this.mail_smtp_ssl_enable = pro.getValue("mail.user");
        this.pwd = pro.getValue("mail.pwd");
        this.reciver = pro.getValue("resive.user");
        this.sender = pro.getValue("mail.user");
    }
    /**
     * 发送简单邮件
     * @param to
     * @param text
     * @throws MessagingException
     *//*
    public  void send_mail(String to,String text) throws MessagingException {
        //创建连接对象 连接到邮件服务器
        Properties properties = new Properties();
        //设置发送邮件的基本参数  
        //发送邮件服务器
        properties.put("mail.smtp.host", mail_smtp_host);
        //发送端口
        properties.put("mail.smtp.port", mail_smtp_port);
        
        properties.put("mail.smtp.socketFactory.fallback", mail_smtp_socketFactory_fallback); // 只处理SSL的连接,对于非SSL的连接不做处理
        properties.put("mail.smtp.auth", mail_smtp_auth);       //是要验证用户名和密码
        properties.put("mail.smtp.ssl.enable", mail_smtp_ssl_enable);   //是否允许使用ssl安全套接字
        //设置发送邮件的账号和密码
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //两个参数分别是发送邮件的账户和密码,密码用授权码
                return new PasswordAuthentication(sender, pwd);
            }
        });
        //创建邮件对象
        Message message = new MimeMessage(session);
        //设置发件人
        message.setFrom(new InternetAddress(sender));
        //设置收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        //设置主题
        message.setSubject("验证码");
        //设置邮件正文  第二个参数是邮件发送的类型
        message.setContent(text,"text/html;charset=UTF-8");
        //发送一封邮件
        Transport.send(message);
    }*/
    
    
    /**
     * 发送带有附件的邮件
     * @param text 邮件的正文
     * @param filePath 邮件的附件
     * @param imageFile 邮件中显示的附件
     */
    public void send_Email_File_image(String to, String text, String imageFile , String filePath){
        
         //创建连接对象 连接到邮件服务器
        Properties properties = new Properties();
        //设置发送邮件的基本参数  
        //发送邮件服务器
        properties.put("mail.smtp.host", mail_smtp_host);
        //发送端口
        properties.put("mail.smtp.port", mail_smtp_port);
        
        properties.put("mail.smtp.socketFactory.fallback", mail_smtp_socketFactory_fallback); // 只处理SSL的连接,对于非SSL的连接不做处理
        properties.put("mail.smtp.auth", mail_smtp_auth);       //是要验证用户名和密码
        properties.put("mail.smtp.ssl.enable", mail_smtp_ssl_enable);   //是否允许使用ssl安全套接字
        //设置发送邮件的账号和密码
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //两个参数分别是发送邮件的账户和密码,密码用授权码
                return new PasswordAuthentication(sender, pwd);
            }
        });
        
        try {
            //创建邮件对象
            Message message = new MimeMessage(session);
            //设置发件人
            message.setFrom(new InternetAddress(sender));
            //设置收件人
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
            //设置主题
            message.setSubject("验证码");
            
            //创建消息部分
            BodyPart bodyPart = new MimeBodyPart();    
            //消息
            bodyPart.setContent(text,"text/html;charset=UTF-8");
            //创建多重消息
            MimeMultipart multiPart_text_image = new MimeMultipart();
            //创建图片部分
            MimeBodyPart image_body = new MimeBodyPart();
            
            image_body.setDataHandler(new DataHandler(new FileDataSource(imageFile)));
            
            //处理附件(路径中文)中文的乱码问题
            
            image_body.setFileName(MimeUtility.encodeText(imageFile));
            
            //设置唯一的编号(在正文节点中引用该编号)
            image_body.setContentID("image001");
            //添加到多重消息里面
            multiPart_text_image.addBodyPart(image_body);
            //添加到多重消息里面
            multiPart_text_image.addBodyPart(bodyPart);
            multiPart_text_image.setSubType("related"); //设置关联关系
            
              // 将 文本+图片 的混合"节点"封装成一个普通"节点"
            // 最终添加到邮件的 Content 是由多个 BodyPart 组成的 Multipart, 所以我们需要的是 BodyPart,
            // 上面的 mailTestPic 并非 BodyPart, 所有要把 mm_text_image 封装成一个 BodyPart
            //所以这里要将多重消息封装成一个普通的节点
            MimeBodyPart mm_text_image = new MimeBodyPart();
            
            mm_text_image.setContent(multiPart_text_image);
            //创建附件部分
            BodyPart file_body = new MimeBodyPart();
            
            //设置要发送的文件的路径
            
            DataSource source = new FileDataSource(filePath);        
            
            file_body.setDataHandler(new DataHandler(source));
            
            //处理附件(路径中文)中文的乱码问题
            file_body.setFileName(MimeUtility.encodeText(filePath));
            
            //创建最终的多重消息,即最后要发送的多重消息
            MimeMultipart multiPart = new MimeMultipart();
            
            //添加到多重消息里面
            multiPart.addBodyPart(file_body);
            multiPart.addBodyPart(mm_text_image);
            multiPart.setSubType("mixed"); //处理文本和附件之间的关系
            //发送完整消息
            message.setContent(multiPart);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        
        
    }
}

测试如下:

mailUtil.send_Email_File_image("1417734497@qq.com", "这个学期的课表<img src='cid:image001'/>","D:/image001.jpg", "D:/url.txt");

结果如下图所示:

 

posted @ 2020-02-19 20:29  陆某人  阅读(333)  评论(0编辑  收藏  举报