互联网科技

java实现发送邮件类

2019-12-23  本文已影响0人  问题_解决_分享_讨论_最优

一、发送邮件的代码

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.io.File;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
 
 
@Component
public class SendMailUtil {
    // 指定发件人电子邮箱
    @Value("${mail.sender}")
    private String from;
    // 指定发送邮件的主机为
    @Value("${mail.mail-server}")
    private String host;
    //指定授权码
    @Value("${mail.accredit-code}")
    private String accreditCode;
 
    public void MailInfo(Map params) throws Exception{
        /** 1、邮箱必要信息初始化 **/
        // 收件人电子邮箱
        String to = params.get("mailhost").toString();
        //指定文件内容
        String content = params.get("content").toString();
        //是否含有附件: 是:true  否:false
        Boolean sw = (Boolean) params.get("sw");
 
        /** 2、系统属性设置 **/
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器类型
        properties.setProperty("mail.smtp.host", host);
        //用户认证
        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(from, accreditCode); //发件人邮件用户名、授权码
            }
        });
 
        /** 3、文件内容设置 **/
        // 创建默认的 MimeMessage 对象
        MimeMessage message = new MimeMessage(session);
        // Set From: 头部头字段
        message.setFrom(new InternetAddress(from));
        // Set To: 头部头字段
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        // Set Subject: 设置邮件主题
        message.setSubject("任务协同提示");
        //设置发送日期
        message.setSentDate(new Date());
        //设置邮件消息体
        MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系
        //设置邮件的mine消息体
        message.setContent(msgMultipart);
        // 设置邮件正文内容
        //message.setText("欢迎使用任务协同系统!");
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(
                "<body>"
                        + "<div style='position: absolute; left: 390px; top: 150px;height:100px;width: 200px;' align='center'>"
                        + "<font color='red'>"+content+"</font>"
                        + "</div>"
                +"</body>",
                "text/html;charset=UTF-8");
        msgMultipart.addBodyPart(htmlPart);
        if(sw) {
            //附件
            MimeBodyPart attach = new MimeBodyPart();
            //把文件,添加到附件中
            //数据源
            FileDataSource ds = new FileDataSource(new File("C:/Users/chewentao/Desktop/temp.txt"));
            //数据处理器
            DataHandler dh = new DataHandler(ds);
            //设置附件的数据
            attach.setDataHandler(dh);
            //设置附件的文件名
            attach.setFileName(MimeUtility.encodeText(dh.getName()));
            msgMultipart.addBodyPart(attach);
        }
        message.saveChanges();
        // 发送消息
        Transport.send(message,message.getAllRecipients());
        System.out.println("Sent message successfully....from runoob.com");
    }
}

二、yml属性

#邮箱发送服务器信息设置
mail:
    mail-server: smtp.qq.com #邮箱服务器
    sender: name@mail.com #发送账户
    accredit-code: zgcwkxijafxvbdii #授权码

三、maven依赖

<!-- javamail-->
<dependency>
   <groupId>com.sun.mail</groupId>
   <artifactId>javax.mail</artifactId>
   <version>1.6.0</version>
</dependency>

四、调用

@Test
public void contextLoads() throws Exception{
   Map map = new HashMap();
   map.put("mailhost","name@mail.com");
   map.put("content","欢迎使用任务协同系统!");
   map.put("sw",true);
   sendMailUtil.MailInfo(map);
}

打个广告,本人博客地址是:风吟个人博客

上一篇下一篇

猜你喜欢

热点阅读