添加样式
def addMailFormt(content): eheader
="<p><b><strong style=\"color:red\">SeaNotification</strong></b></p><br>" efoot="<font color=\"#993300\"> <br> <br> Sincerely,</br> Sea Team</font>" return eheader+content+efoot

 

方式1: Springboot  集成: (优先推荐

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

application.properties

host: smtp.qq.com # 设置邮箱主机(服务商),这里使用QQ邮件服务器

spring.mail.host=192.168.32.253
spring.mail.port=25
spring.mail.from = capi@sea.net
#spring.mail.username=xxxxx@qq.com
# # 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码
#spring.mail.password=xxxxxxxxxxx

 

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class EmailUtils {


    @Value("${spring.mail.from:sea@sea.net}")
    private String sendFrom;
    @Resource
    private JavaMailSender emailSender;
    public Boolean sendMail(String to, String subject, String htmlBody)
    {
        return sendMail(sendFrom, to, subject, htmlBody);
    }

    public Boolean sendMail(String from,String to, String subject, String htmlBody)
    {
        try {
            MimeMessage mimeMessage = emailSender.createMimeMessage();
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlBody, true);
            //添加附件
            // helper.addAttachment("p1.jpg",new File("C:\\Users\\sea\\Pictures\\p1.jpg"));
            // helper.addAttachment("p2.jpg",new File("C:\\Users\\sea\\Pictures\\p2.jpg"));
            emailSender.send(mimeMessage);
            return  true;
        } catch (Exception e) {
            log.error("send mail error : {}",e);
            return  false;
        }
    }
}

 

 

 

方式2  (早些年的写的)

依赖:

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
        </dependency>

 

列如:邮件配置:

application-test.properties

#################Email config start###############################
MAIL_SMTPSERVER=192.168.13.253
##if it is more than one,please separating it by ","  For example "aa@icil.net,bb@icil.net"
MAIL_SEND_TO=qqq.@163.com
MAIL_FROM=www@qq.net
MAIL_SEND_TO_FAIL=afsa2_test@qq.net

#################Email config end###############################

 

 

 

MailUtils:

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
 * ********************************************
 *
 * @ClassName: MailUtils
 *
 * @Description:
 *
 * @author Sea
 *
 * @date 24 Aug 2018 8:34:09 PM
 *
 ***************************************************
 */
@SuppressWarnings("all")
@Component
@Data
public class MailUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailUtils.class);

    public static String MAIL_SMTPSERVER="192.168.32.253";
    public static String MAIL_SEND_TO;
    public static String MAIL_FROM;
    public static String MAIL_SEND_TO_FAIL;

    @Value("${MAIL_SMTPSERVER:192.168.32.253}")
    public void setMAIL_SMTPSERVER(String mailSmtpserver) {
        MAIL_SMTPSERVER = mailSmtpserver;
    }
    @Value("${MAIL_SEND_TO:xx@sea.com}")
    public void setMAIL_SEND_TO(String mailSendTo) {
        MAIL_SEND_TO = mailSendTo;
    }
    @Value("${MAIL_FROM:test@sea.com}")
    public void setMAIL_FROM(String mailFrom) {
        MAIL_FROM = mailFrom;
    }
    @Value("${MAIL_SEND_TO_FAIL:null}")
    public void setMAIL_SEND_TO_FAIL(String mailSendToFail) {
        MAIL_SEND_TO_FAIL = mailSendToFail;
    }


 /**
  * this use default config
  * @param subject
  * @param content
  * @return
  */
    public static boolean sendFailedMail(String subject, String content) {
        return sendMails(MAIL_SEND_TO_FAIL+","+MAIL_SEND_TO, MAIL_FROM, subject, content, null);
    }

    /**
     * @param subject
     * @param content
     * @return
     */
    public static boolean sendMail(String subject, String content) {
        return sendMails(MAIL_SEND_TO, MAIL_FROM, subject, content, null);
    }

    /**
     * @param to
     * @param subject
     * @param content
     * @return
     */
    public static boolean sendMail(String to, String subject, String content) {
        return sendMails(to, MAIL_FROM, subject, content, null);
    }

    /**
     * 带附件
     * @param subject
     * @param content
     * @param filePath
     * @return
     */
    public static boolean sendMail(String to, String subject, String content,List<String> attachfilePaths) {
        return sendMails(to, MAIL_FROM, subject, content, attachfilePaths);
    }


    /**
     * @Description: 发送邮件,发送成功返回true 失败false
     * @param to
     * @param from
     * @param subject
     * @param content
     * @param filenames : ["C:/Users/Sea/Downloads/2.pdf","C:/Users/Sea/Downloads/3.pdf"]
     *  @Date 2018年8月3日
     * @return
     */
    public static boolean sendMails(String to, String from, String subject, String content, List<String> attachfiles) {
        String username = "";
        String password ="";
        LOGGER.info("send mail to : {}",to);
        // 构造mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", MAIL_SMTPSERVER);
//        props.put("mail.smtp.port", "25");// 465
        props.put("mail.smtp.auth","false");

        Session session = null;
        if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(username))
        {
            session = Session.getDefaultInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);}});
        }else {
            session=Session.getDefaultInstance(props);
        }
        try {
            // 构造MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
//            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
//            msg.addRecipients(Message.RecipientType.CC, address);
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            subject = transferChinese(subject);
            msg.setSubject(subject);

            // 构造Multipart
            Multipart mp = new MimeMultipart();
            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content+"", "text/html;charset=utf-8");
            // 向MimeMessage添加(Multipart代表正文)
            mp.addBodyPart(mbpContent);
            // 向Multipart添加附件
            if(attachfiles!=null && attachfiles.size()>0){
                for (String filename : attachfiles)
                {
                    MimeBodyPart mbpFile = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(filename);
                    mbpFile.setDataHandler(new DataHandler(fds));
                    filename = new String(fds.getName().getBytes(), "ISO-8859-1");
                    mbpFile.setFileName(filename);
                    // 向MimeMessage添加(Multipart代表附件)
                    mp.addBodyPart(mbpFile);
                }
            }
            // 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();
            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(MAIL_SMTPSERVER, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            LOGGER.info("send email OK");
        } catch (Exception mex) {
            LOGGER.info("send email is error : {}", mex);
            return false;
        }
        return true;
    }


    /**
     * @param strText
     * @return
     * @Description: 把主题转为中文 utf-8
     * @Date 2017年6月22日 上午10:37:07
     */
    public static String transferChinese(String strText) {
        try {
            strText = MimeUtility.encodeText(new String(strText.getBytes(), "utf-8"), "utf-8", "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strText;
    }

    public static String strong(String value) {
        return "<strong" +value+"</strong>";
    }

    public static String strongRed(String value) {
        return "<b><strong style=\\\"color:red\\\">"+value+"</strong></b>";
    }



    /**
     *
     * @Description:test ok 2018-08-24
     * @author Sea
     * @date 24 Aug 2018 8:34:09 PM
     */
    public static void main(String[] args) {
        boolean mails = new MailUtils().sendMails("sea@sea.net", "test@sea.net", "hello", "I love you sea", Arrays.asList(
                "C:/Users/Sea/Downloads/2.pdf","C:/Users/Sea/Downloads/3.pdf"));
        System.out.println(mails);
        System.err.println("over");
    }

}

 

posted on 2018-09-27 17:35  lshan  阅读(283)  评论(0编辑  收藏  举报