Email工具类

本列是在SpringBoot的基础上建立的,有些缺省参数直接读yml文件,可适当改造
依赖的jar包:org.apache.commons:commons-lang3:3.4 org.apache.commons:commons-email:1.4 org.slf4j:slf4j-api:1.7.24

@Component
public class MailUtil {
    private Logger logger = LoggerFactory.getLogger(MailUtil.class);

    public static final String ENCODEING = "UTF-8";

    @Value("${mail.host:mail.xs.com}")
    private String host; // 服务器地址

    @Value("${mail.sender:admin@xs.com}")
    private String sender; // 发件人的邮箱

    @Value("${mail.nickname:FIY}")
    private String nickname; // 发件人昵称

    @Value("${mail.username:xs}")
    private String username; // 账号

    @Value("${mail.password:xs}")
    private String password; // 密码

    public boolean send(String receiver, String ccReceiver, String subject, String message) {
        if (StringUtils.isBlank(receiver) || StringUtils.isBlank(subject) || StringUtils.isBlank(message)) {
            throw new PosloanException("-9911", "发送邮件接收人,主题,内容都不能为空.");
        }
        HtmlEmail email = new HtmlEmail();
        try {
            // 这里是SMTP发送服务器的名字:163的如下:"smtp.163.com"
            email.setHostName(host);
            // 字符编码集的设置
            email.setCharset(ENCODEING);
            // 收件人的邮箱
            String[] list = StringUtils.split(receiver, ";");
            for (String r : list) {
                if (StringUtils.isNotBlank(r))
                    email.addTo(r);
            }
            if (StringUtils.isNotBlank(ccReceiver)) {
                String[] ccList = StringUtils.split(ccReceiver, ";");
                for (String c : ccList) {
                    if (StringUtils.isNotBlank(c))
                        email.addCc(c);
                }
            }
            // 发送人的邮箱
            email.setFrom(sender, nickname);
            // 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
            email.setAuthentication(username, password);
            // 要发送的邮件主题
            email.setSubject(subject);
            // 要发送的信息,由于使用了HtmlEmail,可以在邮件内容中使用HTML标签
            email.setMsg(message);
            // 发送
            email.send();
            logger.info(sender + " 发送邮件到: " +  MaskUtils.maskString(receiver.toString(), MaskType.EMAIL));
            return true;
        } catch (EmailException e) {
            logger.error(sender + " 发送邮件到: " + MaskUtils.maskString(receiver.toString(), MaskType.EMAIL) + " 失败", e);
            return false;
        }
    }



    //以HTML格式发送邮件
    public boolean sendHtmlWithAttachmentMail(SendMailDto sendMailDto) {
        if (sendMailDto==null || sendMailDto.getReceivers()==null || StringUtils.isBlank(sendMailDto.getSubject())
                || StringUtils.isBlank(sendMailDto.getMessage())) {
            throw new PosloanException("-9911", "发送邮件接收人,主题,内容都不能为空.");
        }
        StringBuffer receivers = new StringBuffer();
        StringBuffer ccReceivers = new StringBuffer();
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setHostName(sendMailDto.getSenderHost());//你的邮件服务器的地址
        htmlEmail.setAuthentication(sendMailDto.getSenderUsername(), sendMailDto.getSenderPassword());//如果你的邮件服务器设置了密码,请输入密码,否则此语句可以忽略
        try {
            for (String r : sendMailDto.getReceivers()) {
                if (StringUtils.isNotBlank(r)){
                    htmlEmail.addTo(r);
                    receivers.append("["+r+"]");
                }
            }
            if (sendMailDto.getCcReceivers()!=null) {
                for (String c : sendMailDto.getCcReceivers()) {
                    if (StringUtils.isNotBlank(c)){
                        htmlEmail.addCc(c);
                        ccReceivers.append(c);
                    }
                }
            }
            htmlEmail.setFrom(sendMailDto.getSenderEmail(), sendMailDto.getSenderNickname());//发件人
            htmlEmail.setCharset("UTF-8");
            htmlEmail.setSubject(sendMailDto.getSubject());
            htmlEmail.setHtmlMsg(sendMailDto.getMessage());
            //是否上传附件
            if(sendMailDto.getAttachments()!=null){
                for(AttachmentDto attachmentDto : sendMailDto.getAttachments()){
                    if(StringUtils.isNotBlank(attachmentDto.getAttachmentPath())
                            && StringUtils.isNotBlank(attachmentDto.getAttachmentShowName())){

                        EmailAttachment attachment = new EmailAttachment();
                       /* try {
                            attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }*/
                        String attachmentPath =  attachmentDto.getAttachmentPath();
                        attachment.setPath(attachmentPath);
                        attachment.setDisposition(EmailAttachment.ATTACHMENT);
                        attachment.setDescription(attachmentDto.getAttachmentShowName());
                        attachment.setName("attachment."+attachmentPath.substring(attachmentPath.lastIndexOf(".")+1));
                        htmlEmail.attach(attachment);//附件
                    }
                }
            }
            if(sendMailDto.getFiles()!=null){
                for(File file :sendMailDto.getFiles()){
                    htmlEmail.attach(file);

                }
            }

            htmlEmail.send();//发送邮件
            logger.info(sender + " 发送邮件到: " + MaskUtils.maskString(receivers.toString(), MaskType.EMAIL) 
            + ",cc: " + MaskUtils.maskString(ccReceivers.toString(), MaskType.EMAIL));
            return true;
        } catch (EmailException e) {
            logger.error(sender + " 发送邮件到: " + MaskUtils.maskString(receivers.toString(), MaskType.EMAIL) 
            + ",cc: " +  MaskUtils.maskString(ccReceivers.toString(), MaskType.EMAIL) + " 失败", e);
            return false;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * 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、付费专栏及课程。

余额充值