使用hutool工具发送带附件的邮件(特简单)

详细代码: https://download.csdn.net/download/qq3892997/86264195

pom.xml:

    <!-- javax.mail版本依赖于Springboot的版本 --> 
     <dependency>
		<groupId>com.sun.mail</groupId>
		<artifactId>javax.mail</artifactId>
	  </dependency>
	  <dependency>
		  <groupId>cn.hutool</groupId>
		  <artifactId>hutool-all</artifactId>
		  <version>5.7.19</version>
	  </dependency>

发送邮件代码:

public SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E"); //年月日  时分秒 周

@Value("${ldt.system.mail}") //properties文件中定义的变量值(邮件发送者)
String sender;
@Value("${spring.mail.host}")
String host;
@Value("${spring.mail.port}")
Integer port;
//以上三个变量都在properties文件中定义,因此当前类必须使用@Component让spring托管,否则@Value是无法获取到配置文件的值,
//如果huToolsendEmail方法被其他类引用了,那么需要使用@Resource引入当前类,请勿使用new xxx()的方法调用当前类的方法,因new对象不是spring托管也是无法获取到@Value的值的

public void huToolsendEmail(String text, File file) {
		System.setProperty("mail.mime.splitlongparameters", "false");//设置系统值 ---处理文件名乱码
		MailAccount account = new MailAccount();
		account.setHost(host);
		account.setPort(port); 
//		account.setAuth(true);//无用户名与密码就必须注释掉auth 否则报错
		account.setFrom(sender);//发送人
		Mail mail = Mail.create(account);
		mail.setFiles(file);//带附件
		mail.setTos("xxxx@xxx.com.xx");//收件人
		mail.setTitle("标题");
		mail.setContent("内容");//如果内容是Html格式,需要把mail.setHtml(true)设置未true,否则格式失效
		mail.setHtml(true);
		mail.send();
	}

如果huToolsendEmail方法所在类不在启动类同模块中,且不想添加注解扫描,那么使用以下类进行获取properties文件内容:

package xxx..xxxxxxx.........xxxxx
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/*获取properties文件中的值
*
* spring托管的类可以直接使用@Value获取到properties内的值,但因为需要在公共模块中写一个公共类获取properties的值,
* 而公共模块意味着跟启动类不是同一个模块(重点是 不是同一个父文件夹),因此没办法被spring扫描到,需要在启动类中添加@MapperScan("xxx.xxx"),而又不想因为这一个类就去扫描这个文件夹
*因此就抛弃了直接使用@Value获取properties值的方式,转而使用以下代码获取配置文件内容
* */
public class ResourceUtil {
    static Properties properties;

    static{
        properties=new Properties();
        InputStream in= ResourceUtil.class.getClassLoader().getResourceAsStream("application.properties");
        try {
            properties.load(in);
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getValue(String key){
        return properties.getProperty(key);
    }

    public static Properties getProperties(){
        return properties;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事不堪回首..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值