javax.mail实现邮件发送

maven相关依赖 spring相关依赖加上邮件依赖,spring就不贴了

<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4.7</version>
</dependency>

mail.properties

#服务器主机名
mail.smtp.host=smtp.163.com
#你的邮箱地址
mail.smtp.username=xxxxxx@163.com
#你的授权码
mail.smtp.password=********
#编码格式
mail.smtp.defaultEncoding=utf-8
#是否进行用户名密码校验
mail.smtp.auth=true
#设置超时时间
mail.smtp.timeout=20000

applicationContext-email.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--邮件配置 -->
    <context:property-placeholder location="classpath:conf/mail.properties" ignore-unresolvable="true" />

    <!--配置邮件接口 -->
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.smtp.host}" />
        <property name="username" value="${mail.smtp.username}" />
        <property name="password" value="${mail.smtp.password}" />
        <property name="defaultEncoding" value="${mail.smtp.defaultEncoding}" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
            </props>
        </property>
    </bean>
</beans>

web.xml

 <!-- 上下文参数 读取Spring配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--启动事物监听器-->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

StringUtils.java

import java.util.UUID;

/**
 * 字符串工具类
 */
public class StringUtils {
/**
     * 获取文件的名字。比如"D:/picture/meizi.jpg"获取到的就是"meizi.jpg"
     *
     * @param str
     *            文件地址
     * @return
     */
    public static String getFileName(String str) {
        //获取"/"字符最后一次出现的位置
        int beginIndex = str.lastIndexOf("/") + 1;
        int endIndex = str.length();
        //截取字符串
        String fileName = str.substring(beginIndex, endIndex);
        return fileName;
    }

    public static String[] getFileName(String[]file) {
        String[]fileName = null;
        if(file != null && file.length > 0){
            fileName = new String[file.length];
            try {
                for (int i=0; i<file.length;i++){
                    int beginIndex = file[i].lastIndexOf("/") + 1;
                    int endIndex = file[i].length();
                    String filepath = file[i].substring(beginIndex, endIndex);
                    fileName[i] = filepath;
                }
                return fileName;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}

SendEmailUtils.java

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;


import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 邮件发送工具类
 */
public class SendEmailUtils {
    /**
     * 发送个人邮件
     * @param text
     * @param subject
     * @param filePath
     * @param emailAdress
     * @param javaMailSender
     * @param type
     * @return
     */
    public String sendMail(String text, String subject, String filePath, String emailAdress,
                           JavaMailSender javaMailSender, Boolean type) {
        MimeMessage mMessage = javaMailSender.createMimeMessage();// 创建邮件对象
        MimeMessageHelper mMessageHelper;
        Properties prop = new Properties();
        try {
            // 从配置文件中拿到发件人邮箱地址
            prop.load(this.getClass().getResourceAsStream("/mail.properties"));
            String from = prop.get("mail.smtp.username") + "";
            mMessageHelper = new MimeMessageHelper(mMessage, true, "UTF-8");
            // 发件人邮箱
            mMessageHelper.setFrom(from);
            // 收件人邮箱
            mMessageHelper.setTo(emailAdress);
            // 邮件的主题也就是邮件的标题
            mMessageHelper.setSubject(subject);
            // 邮件的文本内容,true表示文本以html格式打开
            if (type) {
                mMessageHelper.setText(text, true);
            } else {
                mMessageHelper.setText(text, false);
            }

            // 通过文件路径获取文件名字
            String filename = StringUtils.getFileName(filePath);
            // 定义要发送的资源位置
            File file = new File(filePath);
            FileSystemResource resource = new FileSystemResource(file);
            mMessageHelper.addAttachment(filename, resource);// 在邮件中添加一个附件
            FileSystemResource resource2 = new FileSystemResource("D:/email.txt");
            mMessageHelper.addAttachment("JavaApiRename.txt", resource2);
            // 在邮件中添加一个附件
            javaMailSender.send(mMessage);// 发送邮件
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "发送成功";
    }

    public static InternetAddress[] getMoreAddress(String[] addressStr) {
        InternetAddress[] address = null;
        try {
            List list = new ArrayList<>();//不能使用string类型的类型,这样只能发送一个收件人
            for (int i = 0; i < addressStr.length; i++) {
                list.add(new InternetAddress(addressStr[i]));
            }
            address = (InternetAddress[]) list.toArray(new InternetAddress[list.size()]);
        } catch (AddressException e) {
            e.printStackTrace();
        }
        return address;
    }

    /**
     * 邮件群发
     * @param text
     * @param subject
     * @param filePath
     * @param emailAdress
     * @param javaMailSender
     * @param type
     * @return
     */
    public String sendMailToEveryOne(String text, String subject, String[]filePath, String[] emailAdress,
                           JavaMailSender javaMailSender, Boolean type) {
        MimeMessage mMessage = javaMailSender.createMimeMessage();// 创建邮件对象
        MimeMessageHelper mMessageHelper;
        Properties prop = new Properties();
        InternetAddress[] address = null;
        List list = new ArrayList<>();
        try {
            // 从配置文件中拿到发件人邮箱地址
            prop.load(this.getClass().getResourceAsStream("/mail.properties"));
            String from = prop.get("mail.smtp.username") + "";
            mMessageHelper = new MimeMessageHelper(mMessage, true, "UTF-8");
            // 发件人邮箱
            mMessageHelper.setFrom(from);
            // 收件人邮箱
            if(emailAdress != null && emailAdress.length > 0){
                for (int i = 0; i < emailAdress.length; i++) {
                    list.add(new InternetAddress(emailAdress[i]));
                }
                address = (InternetAddress[]) list.toArray(new InternetAddress[list.size()]);
                mMessageHelper.setTo(address);
            }

            // 邮件的主题也就是邮件的标题
            mMessageHelper.setSubject(subject);
            // 邮件的文本内容,true表示文本以html格式打开
            if (type) {
                mMessageHelper.setText(text, true);
            } else {
                mMessageHelper.setText(text, false);
            }
            String[]filename = null;
            File file = null;
            // 通过文件路径获取文件名字
            if(filePath !=null && filePath.length>0){
                filename = StringUtils.getFileName(filePath);
                for(int i = 0; i < filePath.length; i++){
                    //发送多个附件
                    file = new File(filePath[i]);
                    FileSystemResource resource = new FileSystemResource(file);
                    mMessageHelper.addAttachment(filename[i], resource);
                }
            }
            javaMailSender.send(mMessage);// 发送邮件
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "发送成功";
    }
}

JavaMailTests.java 建一个junit测试类进行测试

import com.reason.utils.SendEmailUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 邮件发送测试类
 */
public class JavaMailTests {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private JavaMailSender javaMailSender;

    @Before
    public void before(){
        applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext-email.xml");
        javaMailSender = (JavaMailSender)applicationContext.getBean("javaMailSender");
    }
    @Test
    public void testSendEmail() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SendEmailUtils sendEmailUtils = new SendEmailUtils();
        String statusCode = sendEmailUtils.sendMailToEveryOne("<h1>现在北京时间是:"+simpleDateFormat.format(new Date())+"</h1>", "放假通知!", new String[]{"D:/meizi.jpg"}, new String[]{"xxxxxx@qq.com"},
                javaMailSender, true);
        System.out.println(statusCode);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值