黑豹程序员-java读取属性配置文件

属性配置

host=smtp.163.com
username=135@163.com
password=tony
port=25

代码

package com.rlcloud.mail;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @version v1.0 创建时间:2023/11/20 15:59
 * @author: 作者:陈子枢
 * @web CSDN:https://blog.csdn.net/nutony
 * @description 描述:读取属性配置文件,发送邮件
 */

@Slf4j
@PropertySource("classpath:mail.properties")
public class MailClient {
    public void sender(String cc, String subject, String html, List<String> attachments) throws javax.mail.MessagingException, IOException {
        Properties prop = new Properties();
        URL url = MailClient.class.getResource("/mail.properties");
        InputStream is = new FileInputStream(url.getPath());
        prop.load(is);

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(prop.getProperty("host"));
        sender.setPort(Integer.valueOf(prop.getProperty("port")));

        sender.setUsername(prop.getProperty("username"));
        sender.setPassword(prop.getProperty("password"));
        sender.setDefaultEncoding("UTF-8");

        // 简化对mimeMessage的封装
        MimeMessage message = sender.createMimeMessage();
        //multipart为true,才能支持多个附件
        MimeMessageHelper helper = new MimeMessageHelper(sender.createMimeMessage(), true, "UTF-8");

        helper.setFrom(sender.getUsername());  //邮件发送人
        helper.setCc(cc);                      //抄送
        helper.setSubject(subject);            //标题
        helper.setText(html,true);       //正文

        //邮件多附件
        for(String attachment: attachments) {
            File file = new File(attachment);
            helper.addAttachment(file.getName(), file);
        }
        sender.send(helper.getMimeMessage());
    }

    public static void main(String[] args) throws Exception {
        MailClient mail = new MailClient();

        List<String> attachments = new ArrayList<>();
        attachments.add("d:\\1.png");
        attachments.add("d:\\2.png");

        mail.sender("[email protected]", "HTML邮件", "

hello,world!

"
,attachments); log.info("邮件发送成功!"); } }

你可能感兴趣的:(黑豹程序员,java基础,java,开发语言,属性文件)