Java发送邮件

本文介绍了一个Java邮件发送系统的实现,包括简单邮件、模板邮件及附件邮件等功能,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java发送邮件

由于项目需要,在网上找了一些Java发送邮件的帖子进行参考和整合,现将该功能实现的源代码贴出来,Mark!

邮件发送接口

主要有 发送模板邮件(简单)、发送模板邮件(带附件)、群发模板邮件(简单)、群发模板邮件(带附件)、发送简单邮件、群发简单邮件、发送附件邮件、群发附件邮件 的功能,根据需求调用即可;

package com.XXX.service.common;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 邮件发送接口
 * 
 * @author gewurong
 * @date 2016年9月28日
 */
public interface MailSenderService {

    /**
     * 发送模板邮件(简单)
     * 
     * @param to
     *            收件人
     * @param subject
     *            邮件主题
     * @param templateLocation
     *            模板路径
     * @param model
     *            数据源
     */
    void sendMailWithTemplate(String to, String subject,
            String templateLocation, Map<String, Object> model);

    /**
     * 发送模板邮件(带附件)
     * 
     * @param to
     *            收件人
     * @param subject
     *            邮件主题
     * @param templateLocation
     *            模板路径
     * @param model
     *            数据源
     * @param attachments
     *            附件集合
     */
    void sendAttachMailWithTemplate(String to, String subject,
            String templateLocation, Map<String, Object> model,
            List<File> attachments);

    /**
     * 群发模板邮件(简单)
     * 
     * @param recipients
     *            收件人集合
     * @param subject
     *            邮件主题
     * @param templateLocation
     *            模板路径
     * @param model
     *            数据源
     */
    void sendMailsWithTemplate(List<String> recipients, String subject,
            String templateLocation, Map<String, Object> model);

    /**
     * 群发模板邮件(带附件)
     * 
     * @param recipients
     *            收件人集合
     * @param subject
     *            邮件主题
     * @param templateLocation
     *            模板路径
     * @param model
     *            数据源
     * @param attachments
     *            附件集合
     */
    void sendAttachMailsWithTemplate(List<String> recipients, String subject,
            String templateLocation, Map<String, Object> model,
            List<File> attachments);

    /**
     * 发送简单邮件
     * 
     * @param to
     *            收件人
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 群发简单邮件
     * 
     * @param recipients
     *            收件人集合
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     */
    void sendSimpleMails(List<String> recipients, String subject, String content);

    /**
     * 发送附件邮件
     * 
     * @param to
     *            收件人
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachments
     *            附件集合
     */
    void sendAttachMail(String to, String subject, String content,
            List<File> attachments);

    /**
     * 群发附件邮件
     * 
     * @param recipients
     *            收件人集合
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachments
     *            附件集合
     */
    void sendAttachMails(List<String> recipients, String subject,
            String content, List<File> attachments);
}

邮件发送接口具体实现

package com.XXX.service.common.impl;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.divingtime.service.common.MailSenderService;
import com.divingtime.utilities.EmailUtils;

@Service
public class MailSenderServiceImpl implements MailSenderService {

    @Resource
    private VelocityEngine velocityEngine;

    @Override
    public void sendMailWithTemplate(String to, String subject,
            String templateLocation, Map<String, Object> model) {
        EmailUtils emailUtils = new EmailUtils();
        String mailContent = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, templateLocation, "utf-8", model);
        emailUtils.sendEmail(to, subject, mailContent);
    }

    @Override
    public void sendAttachMailWithTemplate(String to, String subject,
            String templateLocation, Map<String, Object> model,
            List<File> attachments) {
        EmailUtils emailUtils = new EmailUtils();
        String mailContent = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, templateLocation, "utf-8", model);
        emailUtils.sendEmail(to, subject, mailContent, attachments);

    }

    @Override
    public void sendMailsWithTemplate(List<String> recipients, String subject,
            String templateLocation, Map<String, Object> model) {
        EmailUtils emailUtils = new EmailUtils();
        String mailContent = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, templateLocation, "utf-8", model);
        emailUtils.sendEmail(recipients, subject, mailContent);
    }

    @Override
    public void sendAttachMailsWithTemplate(List<String> recipients,
            String subject, String templateLocation, Map<String, Object> model,
            List<File> attachments) {
        EmailUtils emailUtils = new EmailUtils();
        String mailContent = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, templateLocation, "utf-8", model);
        emailUtils.sendEmail(recipients, subject, mailContent, attachments);

    }

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        EmailUtils emailUtils = new EmailUtils();
        emailUtils.sendEmail(to, subject, content);
    }

    @Override
    public void sendSimpleMails(List<String> recipients, String subject,
            String content) {
        EmailUtils emailUtils = new EmailUtils();
        emailUtils.sendEmail(recipients, subject, content);
    }

    @Override
    public void sendAttachMail(String to, String subject, String content,
            List<File> attachments) {
        EmailUtils emailUtils = new EmailUtils();
        emailUtils.sendEmail(to, subject, content, attachments);
    }

    @Override
    public void sendAttachMails(List<String> recipients, String subject,
            String content, List<File> attachments) {
        EmailUtils emailUtils = new EmailUtils();
        emailUtils.sendEmail(recipients, subject, content, attachments);
    }

}

发送模板邮件用的是Velocity模板引擎,在Maven的pom.xml引入

<!-- 模板引擎 velocity related dependencies -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

具体的模板文件放在resources下的templates目录中

这里写图片描述

需要了解velocity模板引擎的可百度稍微了解下就行了,.vm后缀文件,让前端写好邮件模板的html文件(尽量使用内联样式),修改后缀为vm,然后嵌套数据即可,如$nickname

这里写图片描述

邮件发送工具类

package com.XXX.utilities;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 javax.mail.internet.MimeUtility;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

import com.sun.mail.util.MailSSLSocketFactory;

/**
 * 邮箱工具类
 * 
 * @author gewurong
 * @date 2016年9月20日
 * 
 */
public class EmailUtils {

    private static String nickname;// 默认帐号昵称
    private static String account;// 登录用户帐号
    private static String passwd;// 登录帐号密码
    private static String from;// 发件地址
    private static String protocol;// 协议
    private static String host;// 服务器地址
    private static String port; // 端口

    private static final String KEY_PROTOCOL = "mail.transport.protocol";
    private static final String KEY_HOST = "mail.smtp.host";
    private static final String KEY_PORT = "mail.smtp.port";
    private static final String KEY_AUTH = "mail.smtp.auth";
    private static final String KEY_SSL_ENABLE = "mail.smtp.ssl.enable";
    private static final String KEY_SSL_SOCKETFACTORY = "mail.smtp.ssl.socketFactory";

    // 会话
    private Session session;
    private MimeMessage message;

    private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());

    // 初始化邮件属性
    static {

        // 加载属性文件
        Properties props = null;
        try {
            props = AppPropertiesUtil.getAppProps(EmailUtils.class,
                    "conf/email.properties");
        } catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("Failed:加载邮件属性文件失败!");
        }

        nickname = props.getProperty("email.nickname");
        account = props.getProperty("email.account");
        passwd = props.getProperty("email.passwd");
        from = props.getProperty("email.from");
        protocol = props.getProperty("email.protocol");
        host = props.getProperty("email.host");
        port = props.getProperty("email.port");

    }

    public EmailUtils() {

        Properties props = new Properties();
        // 协议
        props.setProperty(EmailUtils.KEY_PROTOCOL, protocol);
        // 服务器
        props.setProperty(EmailUtils.KEY_HOST, host);
        // 端口
        props.setProperty(EmailUtils.KEY_PORT, port);
        // 使用smtp身份验证
        props.setProperty(EmailUtils.KEY_AUTH, "true");

        // 使用腾讯企业邮箱,基于SSL
        // 开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }

        props.put(EmailUtils.KEY_SSL_ENABLE, "true");
        props.put(EmailUtils.KEY_SSL_SOCKETFACTORY, sf);

        session = Session.getDefaultInstance(props, new MyAuthericator(account,
                passwd));
        session.setDebug(true);// 启动打印调试信息

        message = new MimeMessage(session);
    }

    /**
     * 用户名密码验证, 实现抽象类Authenticator的抽象方法PasswordAuthentication
     */
    static class MyAuthericator extends Authenticator {
        String user = null;
        String password = null;

        public MyAuthericator(String user, String password) {
            this.user = user;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
        }
    }

    /**
     * 发送简单邮件
     * 
     * @param to
     *            收件人邮箱
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     */
    public void sendEmail(String to, String subject, String content) {
        try {

            // 发件人
            message.setFrom(new InternetAddress(from, nickname));// 邮箱地址,默认帐号昵称
            // 收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                    to));
            // 邮件标题
            message.setSubject(subject);
            // 邮件日期
            message.setSentDate(new Date());
            // 邮件内容
            message.setContent(content, "text/html;charset=UTF-8");
            message.saveChanges();
            Transport.send(message);
            logger.info("发送成功:  发件人:{}|收件人:{}", from, to);
        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
            logger.error("发送失败:{},错误信息:{}", from, e.getMessage());
        }
    }

    /**
     * 简单邮件群发
     * 
     * @param recipients
     *            收件人集合
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     */
    public void sendEmail(List<String> recipients, String subject,
            String content) {
        try {

            // 发件人
            message.setFrom(new InternetAddress(from, nickname));// 邮箱地址,默认帐号昵称
            // 收件人
            InternetAddress[] addresses = new InternetAddress[recipients.size()];
            for (int i = 0; i < addresses.length; i++) {
                addresses[i] = new InternetAddress(recipients.get(i));
            }
            message.addRecipients(Message.RecipientType.TO, addresses);
            // 邮件标题
            message.setSubject(subject);
            // 邮件日期
            message.setSentDate(new Date());
            // 邮件内容
            message.setContent(content, "text/html;charset=UTF-8");
            message.saveChanges();
            Transport.send(message);
            logger.info("发送成功:  发件人:{}|收件人:{}", from, addresses);
        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
            logger.error("发送失败:{},错误信息:{}", from, e.getMessage());
        }
    }

    /**
     * 发送带附件邮件
     * 
     * @param to
     *            收件人邮箱
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachments
     *            附件集合
     */
    public void sendEmail(String to, String subject, String content,
            List<File> attachments) {
        try {

            // 发件人
            message.setFrom(new InternetAddress(from, nickname));// 邮箱地址,默认帐号昵称
            // 收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                    to));
            // 邮件标题
            message.setSubject(subject);
            // 邮件日期
            message.setSentDate(new Date());

            // 邮件内容
            Multipart multipart = new MimeMultipart();
            // --邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            // --邮件附件
            if (attachments != null) {
                for (File attachment : attachments) {
                    BodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentPart.setDataHandler(new DataHandler(source));

                    // 避免中文乱码
                    attachmentPart.setFileName(MimeUtility
                            .encodeWord(attachment.getName()));

                    multipart.addBodyPart(attachmentPart);
                }
            }
            message.setContent(multipart);
            message.saveChanges();
            Transport.send(message);
            logger.info("发送成功:  发件人:{}|收件人:{}", from, to);
        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
            logger.error("发送失败:{},错误信息:{}", from, e.getMessage());
        }
    }

    /**
     * 群发带附件邮件
     * 
     * @param recipients
     *            收件人集合
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachments
     *            附件集合
     */
    public void sendEmail(List<String> recipients, String subject,
            String content, List<File> attachments) {
        try {

            // 发件人
            message.setFrom(new InternetAddress(from, nickname));// 邮箱地址,默认帐号昵称
            // 收件人
            InternetAddress[] addresses = new InternetAddress[recipients.size()];
            for (int i = 0; i < addresses.length; i++) {
                addresses[i] = new InternetAddress(recipients.get(i));
            }
            message.addRecipients(Message.RecipientType.TO, addresses);
            // 邮件标题
            message.setSubject(subject);
            // 邮件日期
            message.setSentDate(new Date());

            // 邮件内容
            Multipart multipart = new MimeMultipart();
            // --邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            // --邮件附件
            if (attachments != null) {
                for (File attachment : attachments) {
                    BodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentPart.setDataHandler(new DataHandler(source));

                    // 避免中文乱码
                    attachmentPart.setFileName(MimeUtility
                            .encodeWord(attachment.getName()));

                    multipart.addBodyPart(attachmentPart);
                }
            }
            message.setContent(multipart);
            message.saveChanges();
            Transport.send(message);
            logger.info("发送成功:  发件人:{}|收件人:{}", from, addresses);
        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
            logger.error("发送失败:{},错误信息:{}", from, e.getMessage());
        }
    }
}

邮件属性文件email.properties

将对应属性更换为自己的就行了,本人用的是腾讯企业邮箱,另外记得开启对应邮箱的SMTP服务

email.nickname=公司名称/发送人名称、昵称等
email.account=发送邮件的邮箱账号
email.passwd=邮箱密码
email.from=发送邮件的邮箱账号
email.host=smtp.exmail.qq.com
email.port=465
email.protocol=smtp

使用案例

该例子为发送模板邮件,其他功能以此类推

//嵌套数据
Map<String, Object> model = new HashMap<>();
model.put("mobile", admin.getMobile());
model.put("nickName", admin.getNickname());
//附件
List<File> attachments = new ArrayList<>();
file = new File("文件");
attachments.add(file);
//发送模板邮件
mailSenderService.sendAttachMailWithTemplate("接收邮箱123456@qq.com","邮件标题", "模板路径", model,attachments);

END —我—————是—————有—————底—————线—————的

/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值