基于javax的邮件服务

后续,应该会写个基于springBoot的邮件服务,这个就不详细说了,引入javax里面的那个邮件包,引入下 基本就行了。

实现类:

package com.mocha.cms.utils;

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    /**
     * 发送邮件
     * 
     * @param subject 主题
     * @param toUsers  收件人
     * @param ccUsers 抄送
     * @param content 邮件内容
     * @param attachfiles 附件列表 List> key: name && file
     */
    public static boolean sendEmail(String subject, String[] toUsers, String[] ccUsers, String content,
            List> attachfiles) {
        boolean flag = true;
        try {
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setHost(PropertyUtil.getValue("mail.host"));
            javaMailSender.setUsername(PropertyUtil.getValue("mail.auth.name"));
            javaMailSender.setPassword(PropertyUtil.getValue("mail.auth.password"));
            javaMailSender.setDefaultEncoding(PropertyUtil.getValue("mail.send.charset"));
            javaMailSender.setProtocol(PropertyUtil.getValue("mail.transport.protocol"));
            javaMailSender.setPort(465);

            Properties properties = new Properties();
            properties.setProperty("mail.smtp.auth", PropertyUtil.getValue("mail.auth.name"));
            properties.setProperty("mail.smtp.timeout", PropertyUtil.getValue("mail.smtp.timeout"));
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                properties.put("mail.smtp.ssl.enable", "true");
                properties.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            };
            javaMailSender.setJavaMailProperties(properties);

            MimeMessage mailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
            messageHelper.setTo(toUsers);
            if (ccUsers != null && ccUsers.length > 0) {
                messageHelper.setCc(ccUsers);
            }
            messageHelper.setFrom(PropertyUtil.getValue("mail.auth.name"));
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);

            if (attachfiles != null && attachfiles.size() > 0) {
                for (Map attachfile : attachfiles) {
                    String attachfileName = attachfile.get("name");
                    File file = new File(attachfile.get("file"));
                    messageHelper.addAttachment(attachfileName, file);
                }
            }
            javaMailSender.send(mailMessage);

        } catch (Exception e) {
            logger.error("发送邮件失败!", e);
            flag = false;
        }
        return flag;
    }
    
    
    public static void main(String[] args) {
        String[] toUsers = new String[1];
        toUsers[0] = "[email protected]";
        EmailUtils.sendEmail("test", toUsers, null, "text-content", null);
    }
}

配置文件:

mail.host=smtp.163.com
[email protected]
mail.auth.password=授权码
mail.smtp.auth=true
mail.transport.protocol=smtp
mail.send.charset=UTF-8
mail.smtp.timeout=5000

----------或者实现类--------

实现类:

@Override
    public void sendEamil(Mail mail, List fileName) {
        // 与smtp服务器建立一个链接
        Properties p = new Properties();
        try {
            // 指定邮件服务器,默认端口 25
            p.setProperty("mail.host", PropertyUtil.getValue("mail_host"));
            // 要采用指定用户名密码的方式去认证
            p.setProperty("mail.smtp.auth", "true");
            // 发送邮件协议名称
            p.setProperty("mail.transport.protocol", "smtp");
            // 开启SSL加密,否则会失败
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.enable", "true");
            p.put("mail.smtp.ssl.socketFactory", sf);
            // 创建session
            Session session = Session.getInstance(p);
            // 通过session得到transport对象
            Transport ts = session.getTransport();
            // 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
            ts.connect(PropertyUtil.getValue("mail_host"), PropertyUtil.getValue("mail_username"), PropertyUtil.getValue("mail_password"));
            // 声明一个Message对象(代表一封邮件),从session中创建
            MimeMessage msg = new MimeMessage(session);
            // 邮件信息封装
            // 1发件人
            msg.setFrom(new InternetAddress(PropertyUtil.getValue("mail_username")));
            // 2收件人
            msg.setRecipient(RecipientType.TO, new InternetAddress(PropertyUtil.getValue("mail_addr")));
            // 3邮件内容:主题
            msg.setSubject(mail.getSubject());
            // 邮件内容部分1---文本内容
            MimeBodyPart body0 = new MimeBodyPart(); // 邮件中的文字部分
            body0.setContent(mail.getContent(), "text/html;charset=utf-8");
            MimeMultipart mm = new MimeMultipart();
            mm.addBodyPart(body0);
            // 添加附件部分
            List listFile = mail.getListFile();
            if(listFile != null && !listFile.isEmpty()) {
                int index = 0;
                for (File file : listFile) {
                    MimeBodyPart body = new MimeBodyPart();
                    body.setDataHandler(new DataHandler(new FileDataSource(file)));
                    body.setFileName(fileName.get(index));
                    mm.addBodyPart(body);
                    index++;
                };
            }
            msg.setContent(mm);
            // 发送邮件
            ts.sendMessage(msg, msg.getAllRecipients());
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

配置文件:

#邮箱服务器地址#
#mail_host=smtp.nx.chinamobile.com
#发件人用户名#  
#[email protected]
#授权码/密码#  
#mail_password=授权码
#收件人#
#[email protected]

你可能感兴趣的:(基于javax的邮件服务)