浅谈_Java中的邮件发送

浅谈_Java中的邮件发送

    本博客仅仅是个人工作的一些总结,在创作过程中同样借鉴了一些前辈的文档,如有不全面或是遗漏的地方还望各位读者指正~

相信很多同学都会遇到在程序中需要发送邮件的需求,  这里总结了两种发送邮件的方式:

一:使用JavaxMail进行邮件的发送

二:使用Spring封装的JavaMailSender进行邮件的发送

浅谈_一:使用JavaxMail进行邮件的发送

一__设置好邮箱的SMTP/POP3/IMAP协议的授权

这里要提一下,有些邮箱账号的密码是需要填写生成的授权码的(比如个人的QQ邮箱),

而有些邮箱地址需要填写邮箱账号的登录密码(比如腾讯企业邮箱,新浪邮箱),

网易的邮箱没有进行具体发送邮件的测试,如有需要,请读者自行测试.

新浪邮箱的设置:

浅谈_Java中的邮件发送_第1张图片

个人QQ邮箱的设置:

浅谈_Java中的邮件发送_第2张图片

腾讯企业邮箱不需要设置(官方说明中表明已经做好相应的配置,用户直接使用即可)

二__天才第一步_引入spring_context和javaxmail的依赖

     
        org.springframework
        spring-context-support
        4.3.8.RELEASE
    

    
        javax.mail
        mail
        1.6.0
    

这里使用的是javax.mail-1.6.0.jar

三__工具类代码

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 使用JavaxMail实现发送邮件的工具类
 */

public class MailUtil {

    // properties配置文件地址
    //private static final String PROPERTIES_PATH = "standard_data.properties";

    private static Session session;
    private static Properties props = new Properties();
    //发送邮件的服务器地址
    private static final String HOST = "smtp.sina.com";
    //端口号
    private static int PORT = 587;
    //授权
    private static final String isAUTH = "true";
    //发送端地址
    private static final String FROM = "**************";
    //用户名(邮箱账号)
    private static final String USERNAME = "*********";
    //密码    个人QQ邮箱以及某些邮箱(具体看邮箱的设置)需要授权码,其他邮箱需要登录密码
    private static final String PASSWORD = "************";
    //延迟
    private static final String TIMEOUT = "25000";
    //Debug调试模式
    private static final String DEBUG = "true";

    // 初始化session
    static {
        //设置邮件会话属性
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", isAUTH);
        props.put("fromer", FROM);
        props.put("username", USERNAME);
        props.put("password", PASSWORD);
        props.put("mail.smtp.timeout", TIMEOUT);
        props.put("mail.debug", DEBUG);
        //通过在session中注册一个用户名,密码的认证器,初始化session
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });
        //设置调试模式,发布时取消
        //session.setDebug(true);
    }



    /**
     *
     * @Title sendEmail
     * @Description 通过isHtml判断发送的邮件的内容
     * @param to 邮件接收者
     * @param content 邮件内容
     * @param isHtml 是否发送html
     * @throws MessagingException
     * @throws IOException
     * @throws FileNotFoundException
     * @throws EmailException
     */
    public static void sendEmail(String to, String title, String content, boolean isHtml)
            throws FileNotFoundException, IOException, MessagingException {
        String fromer = props.getProperty("fromer");
        if (isHtml) {
            sendHtmlEmail(to, title, content);
        } else {
            sendTextEmail(to, title, content);
        }
    }

    // 发送纯文字邮件
    public static void sendTextEmail(String to, String subject, String content)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setText(content);
        message.setSentDate(new Date());
        Transport.send(message);
    }

    // 发送有HTML格式邮件
    public static void sendHtmlEmail(String to, String subject, String htmlConent)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());

        Multipart multi = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(htmlConent, "text/html; charset=utf-8");
        multi.addBodyPart(html);
        message.setContent(multi);
        Transport.send(message);
    }

    // 发送带附件的邮件
    public static void sendFileEmail(String to, String subject, String htmlConent, File attachment)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        String fromer = props.getProperty("fromer");
        message.setFrom(new InternetAddress(fromer));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart();
        // 添加邮件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(htmlConent, "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);
        // 添加附件的内容
        if (attachment != null) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            attachmentBodyPart.setDataHandler(new DataHandler(source));

            // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
            // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
            //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            //attachmentBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
            // MimeUtility.encodeWord可以避免中文文件名乱码
            attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
            multipart.addBodyPart(attachmentBodyPart);
        }
        message.setContent(multipart);
        Transport.send(message);
    }


    // 发送纯文字邮件,可以添加抄送地址
    public static void sendTextEmailAndCC(String to, Address[] CCs,String subject, String content)
            throws FileNotFoundException, IOException, MessagingException {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));

        if(CCs != null && CCs.length > 0) {
            message.addRecipients(Message.RecipientType.CC,CCs);
        }

        /*//添加抄送地址
        String cc1 = "[email protected]";
        Address address_cc1 = new InternetAddress(cc1);
        Address[] cc = {address_cc1};
        message.addRecipients(Message.RecipientType.CC,cc);*/

        message.setSubject(subject);
        message.setText(content);
        message.setSentDate(new Date());
        Transport.send(message);
    }


}

浅谈_二:使用Spring封装的JavaMailSender进行邮件的发送

一__设置好邮箱的SMTP/POP3/IMAP协议的授权

此处如上所述,略

二__引入依赖

此处如上所述,略

三__配置applicationContext-mail.xml文件(可选操作,也可以在类中进行配)

    
        
        //或许你可以用465端口,默认的25不适合
        
        //邮箱账号
        //QQ个人邮箱需要授权码,腾讯企业邮箱需要登录密码
        
          
              
                true 
                25000  
              
          

    
四__工具类代码
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
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 javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.Date;
import java.util.Properties;

/**
 * 使用Spring的JavaMail发送邮件的工具类
 */
public class EmailUtil {

    //邮箱发送服务器   QQ企业邮箱
    private static final String HOST = "smtp.exmail.qq.com";
    //邮箱接收服务器   QQ企业邮箱
    private static final String REV = "imap.exmail.qq.com";
    //协议类型
    private static final String PROTOCOL = "smtp";
    //端口
    private static final int PORT = 587;//465
    //发送邮件地址
    private static final String FROM = "**********";
    //用户名
    private static final String USERNAME = "**********";
    //密码_QQ邮箱必须填写授权码_QQ企业邮箱填写登录密码即可
    private static final String PASSWORD = "*********";
    //字符集
    private static final String ENCODE = "UTF-8";
    //邮件抄送地址
    private static final String CC = "**********";
    //邮件密送地址
    private static final String BCC = "********";
    //系统属性
    private static final String AUTH = "true";
    private static final String TIMEOUT = "25000";

    //创建一个JavaMailSenderImpl对象,该对象实现了JavaMailSender接口
    private static JavaMailSenderImpl sender = new JavaMailSenderImpl();

    //创建一个系统属性集
    private static Properties prop = new Properties();

    static {
        //设置邮件服务器参数
        sender.setHost(HOST);
        sender.setProtocol(PROTOCOL);
        sender.setPort(PORT);
        sender.setUsername(USERNAME);
        sender.setPassword(PASSWORD);
        sender.setDefaultEncoding(ENCODE);
        //设置系统属性
        prop.put("mail.smtp.auth",AUTH);
        prop.put("mail.smtp.timeout",TIMEOUT);
        prop.put("mail.smtps.ssl.enable", "true");
        //设置调试模式可以在控制台查看发送过程
        prop.put("mail.debug", "true");
        sender.setJavaMailProperties(prop);
    }

    /**
     * 发送普通文本的邮件
     * @param to
     * @param subject
     * @param text
     * @return
     */
    public static boolean sendTextMail(String[] to,String subject,String text) {
        boolean result = true;
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(FROM);
        message.setTo(to);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(text);
        try {
            sender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    /**
     * 发送html格式的邮件
     * @param to
     * @param subject
     * @param html
     * @return
     */
    public static boolean sendHtmlMail(String[] to,String subject,String html) {
        boolean result = true;
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {
            messageHelper.setFrom(FROM);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(html,true);
            messageHelper.setSentDate(new Date());
            sender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    /**
     * 发送带内嵌图片的邮件
     * html中src:cid的数据需要与addInline()中第一个参数一致
     * @param to
     * @param subject
     * @param filePath
     * @param html
     * @return
     */
    public static boolean sendPicMail(String[] to,String subject,String filePath,String html) {
        boolean result = true;
        MimeMessage mailMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);
            messageHelper.setFrom(FROM);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(html,true);
            //FileSystemResource file = new FileSystemResource(new File(filePath));
            FileSystemResource file = new FileSystemResource(filePath);
            String filename = file.getFilename();
            messageHelper.addInline(filename,file);
            sender.send(mailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }


    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param filePath
     * @param html
     * @return
     */
    public static boolean sendFileMail(String[] to,String subject,String filePath,String html) {
        boolean result = true;
        MimeMessage mailMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"UTF-8");
            messageHelper.setFrom(FROM);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(html,true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String filename = file.getFilename();
            //如果附件的中文名乱码
            //String filename = MimeUtility.encodeWord(file.getFilename());
            messageHelper.addAttachment(filename,file);
            sender.send(mailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }


}

注:在发送带内嵌图片的邮件时,传入的html参数中的,需要与addInline()方法中的第一个参数完全一致,否则图片无法显示!!!

这里附上借鉴的另一篇关于发送邮件的优秀博客:

https://blog.csdn.net/caimengyuan/article/details/51224269点击打开链接

JavaAPI的详解:

https://blog.csdn.net/imain/article/details/1453677点击打开链接

Ps : javax.mail.jar的版本过低会出现问题,最开始用的1.3.0的版本就出现了各种问题,搞了好久发现是版本过低了.............



你可能感兴趣的:(工具类)