本文主要是介绍黑豹程序员-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("52399178@qq.com", "HTML邮件", "<h1 style='color:red'>hello,world!</h1>",attachments);log.info("邮件发送成功!");}}
这篇关于黑豹程序员-java读取属性配置文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!