技术积累系列(二)------Java实现发邮件且可以添加附件

1.初步学习实现方式

(1)首先发送邮件需要开启smpt或者pop3协议,这里我以qq为例。
这里写图片描述
开启后会得到一个授权码,这个授权码一会要配置到java代码里。
(2)导入所需的mail.jar的相关架包。
(3)上代码

package com.neu.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class JavaEmailSender {
    public static void sendEmail(String toEmailAddress,String emailTitle,String emailContent)throws Exception{
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        /**SSL认证,注意腾讯邮箱是基于SSL加密的,所有需要开启才可以使用**/
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        //创建会话
        Session session = Session.getInstance(props);

        //发送的消息,基于观察者模式进行设计的
        Message msg = new MimeMessage(session);
        msg.setSubject(emailTitle);
        //使用StringBuilder,因为StringBuilder加载速度会比String快,而且线程安全性也不错
        StringBuilder builder = new StringBuilder();
        builder.append("\n"+emailContent);
        builder.append("\n时间 " + new Date());
        msg.setText(builder.toString());
        msg.setFrom(new InternetAddress("你的qq邮箱@qq.com"));

        Transport transport = session.getTransport();
        transport.connect(**"smtp.qq.com", "你的qq邮箱@qq.com", "你的授权码*****");
        //发送消息
        transport.sendMessage(msg, new Address[] { new InternetAddress(toEmailAddress) });
        transport.close();
}
}

这样就能发送一封邮件啦,当然,这只是初步学习的尝试,功能很单一。

2.深入学习后实现方式

(1)可以添加附件,可以发送给多个邮箱。

package com.apex.utils;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

/**
 * @desc: Project
 * @author: hj
 * @createTime: 2018年8月1日 下午12:06:10
 * @version: v1.0
 */
public class MailServiceUtil {
    private static final Logger LG = Logger.getLogger(MailServiceUtil.class);
    public String sendMail(String to, String sub, String content,String filepath){
        LG.info("开始发送邮件,内容:"+content);
        try {
            // 1.创建一个程序与邮件服务器会话对象 Session
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol","smtp");
            props.setProperty("mail.smtp.host", PropertyUtil.getProperty("mail.smtp.host"));
            props.setProperty("mail.smtp.port", "25");
            // 指定验证为true
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.timeout", "1000");

            Session session = Session.getInstance(props);
            // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);
            // 2、通过session得到transport对象
            Transport ts = session.getTransport();
            // 3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器
            ts.connect(PropertyUtil.getProperty("mail.smtp.host"),
                    PropertyUtil.getProperty("mail.username"), 
                    PropertyUtil.getProperty("mail.password"));
            // 4、创建邮件
            Message message = createSimpleMail(session,to,sub,content,filepath);
            // 5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
            LG.info("发送邮件成功...");
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            LG.info("发送邮件失败,异常信息:"+e.getMessage());
            return "FAIL";
        }
    }

    public static MimeMessage createSimpleMail(Session session,String to, String sub, String content,String filepath)
            throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress(PropertyUtil.getProperty("mail.username")));
        // 指明邮件的收件人
        String[] tos = to.split(";");
        Address aaddress[] = new Address[tos.length];
        for (int i = 0; i < tos.length; i++) {
            aaddress[i] = new InternetAddress(tos[i]);
        }
        message.setRecipients(Message.RecipientType.TO,aaddress);
        // 邮件的标题
        message.setSubject(sub);
        // 邮件的文本内容
        //message.setContent(content, "text/html;charset=UTF-8");
        // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart(); 
        // 添加邮件正文
        BodyPart contentBodyPart = new MimeBodyPart();
        contentBodyPart.setContent(content, "text/html;charset=UTF-8");
        multipart.addBodyPart(contentBodyPart);    
        // 添加附件
        if (filepath != null && !"".equals(filepath)) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            // 根据附件路径获取文件,
            FileDataSource dataSource = new FileDataSource(filepath);
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            //MimeUtility.encodeWord可以避免文件名乱码
            attachmentBodyPart.setFileName(MimeUtility.encodeWord(dataSource.getFile().getName()));
            multipart.addBodyPart(attachmentBodyPart);
        }
        // 邮件的文本内容
        message.setContent(multipart);

        // 返回创建好的邮件对象
        return message;
    }

    public static void main(String[] args) {
        System.out.println(
                new MailServiceUtil().
                sendMail("测试邮箱@qq.com;测试邮箱@apexsoft.com.cn","主題:測試","<p>您好!<br/>测试邮件,附件为Excel附件注意查收!</p><a href='#'>点击此处 </a>","附件目录"));
    }

}

(2)上一段代码用到的工具类PropertyUtil

/*
 * Copyright @ 2018 com.apexsoft document 下午3:14:13 All right reserved.
 */
package com.apex.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 * @desc: Project
 * @author: hj
 * @createTime: 2018年8月1日 下午12:06:10
 * @version: v1.0
 */
public final class PropertyUtil {
    private static final Logger LG = Logger.getLogger(PropertyUtil.class);

    private static String defaultFile = "apexmail.properties";

    /**
     * constructor of PropertyUtil.java
     */
    private PropertyUtil() {}

    private static Properties props;
    static {
        loadProps(defaultFile);
    }

    synchronized static private void loadProps(String fileName) {
        System.out.println("开始加载properties文件内容.......");
        if(props == null)
        {
            props = new Properties();
        }
        InputStream in = null;
        try {
            in = PropertyUtil.class.getClassLoader()
                    .getResourceAsStream(fileName);
            props.load(in);
        } catch (FileNotFoundException e) {
            LG.error(fileName+"文件未找到,"+e.getMessage());
        } catch (IOException e) {
            LG.error("出现IOException"+e.getMessage());
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                LG.error("文件流关闭出现异常,"+e.getMessage());
            }
        }
        System.out.println("加载properties文件内容完成...........");
        System.out.println(props);
    }

    public static void appendProps(String fileName) {
            loadProps(fileName);
    }

    public static String getProperty(String key) {
        if (null == props) {
            loadProps(defaultFile);
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps(defaultFile);
        }
        return props.getProperty(key, defaultValue);
    }

    public static void clear() {
        if (null == props) {
            props.clear();
        }
    }

}

自己配置的连接邮箱的properties文件

mail.smtp.host=mail.****.com.cn
mail.username=*****@apexsoft.com.cn
mail.password=*****
这里涉及个人邮箱隐私,我都注释*号

猜你喜欢

转载自blog.csdn.net/qq_21786329/article/details/81357805