环境
邮件发送人要动态设置,登陆人是谁发送人就是谁。
这就需要配置文件可修改
配置文件
SpringMVC
properties
prop.file=xxx.properties #本properties配置文件的名字
email.host=smtp.163.com
email.port=25
email.username=xxx@163.com
email.password=xxx
email.smtpAuth=true
email.smtpConnectiontimeout=800000
email.smtpTimeout=800000
email.smtpwritetimeout=800000
email.smtp.starttls.enable=true
<!--邮件发送 -->
<util:properties id="config" location="classpath:xxx.properties" />
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="#{config['email.host']}"/>
<property name="port" value="#{config['email.port']}"/>
<property name="username" value="#{config['email.username']}"/>
<property name="password" value="#{config['email.password']}"/>
<property name="javaMailProperties">
<props >
<prop key="mail.smtp.auth">#{config['email.smtpAuth']}</prop>
<prop key="mail.smtp.connectiontimeout">#{config['email.smtpConnectiontimeout']}</prop>
<prop key="mail.smtp.timeout">#{config['email.smtpTimeout']}</prop>
<prop key="mail.smtp.writetimeout">#{config['email.smtpwritetimeout']}</prop>
<!-- <prop key="sendFrom">#{config['email.username']}</prop> -->
</props>
</property>
</bean>
SpringBoot
1. 类似上面springmvc
appliction.yml
spring:
profiles:
active: email #引入另外一个同路径下yml配置文件,该配置文件必须以application-开头
#配置邮件发送
mail:
host: smtp.qiye.163.com # 163邮箱smtp主机
port: 25 #qq端口号465或587
# username: xxx
# password: xxx # 这里QQ邮箱开通POP3/SMTP提供的授权码,如果邮箱服务商没有授权码,可以使用密码代替
protocol: smtp
default-encoding: UTF-8
appliction-email.yml
prop:
file: application-email.yml
#spring
spring:
#配置邮件发送
mail:
username: xxx
password: xxx
2.
appliction.yml
spring:
#配置邮件发送
mail:
host: smtp.qiye.163.com # 163邮箱smtp主机
port: 25 #qq端口号465或587
username: xxx
password: xxx # 这里QQ邮箱开通POP3/SMTP提供的授权码,如果邮箱服务商没有授权码,可以使用密码代替
protocol: smtp
default-encoding: UTF-8
方法
SpringMVC
// 或${prop.file}
public MyResult setSMTPInfo(SMTPInfo smtpInfo,@Value("#{config['prop.file']}") String propfileName){
Resource propertiesFile = new ClassPathResource(propfileName);
Properties fileProp = new Properties();
try {
File outfile = propertiesFile.getFile();
fileProp.load(new FileInputStream(outfile));
javaMailSender.setHost(smtpInfo.getHost());
fileProp.setProperty("email.host", smtpInfo.getHost());
javaMailSender.setPort(smtpInfo.getPort());
fileProp.setProperty("email.port", ""+smtpInfo.getPort());
javaMailSender.setUsername(smtpInfo.getUsername());
fileProp.setProperty("email.username", ""+smtpInfo.getUsername());
javaMailSender.setPassword(smtpInfo.getPassword());
fileProp.setProperty("email.password", ""+smtpInfo.getPassword());
Properties prop = new Properties();
prop.setProperty("mail.smtp.auth", smtpInfo.getSmtpAuth());
javaMailSender.setJavaMailProperties(prop);
fileProp.setProperty("email.smtpAuth", ""+smtpInfo.getSmtpAuth());
OutputStream fos = new FileOutputStream(outfile);
fileProp.store(fos, "file updated on" + new Date());
} catch (IOException e) {
logger.error(e.getMessage(), e);
return new MyResult(-1,e.getMessage());
}
return new MyResult(1,"已成功设置邮件发送服务器!");
}
上面为接口,可写页面做修改,这些信息修改是修改的编译后文件内容,所以重新发布后,这些配置信息还为原文件内容,除非发布前将配置信息更改为对应的修改信息。
SpringBoot
1. 类似上面springmvc
@Autowired
private JavaMailSenderImpl mailSender;
/**
* 后加的防止题目过长并且进行全局定义
*/
static {
System.setProperty("mail.mime.splitlongparameters", "false");
System.setProperty("mail.mime.charset", "UTF-8");
}
/**
* 发送简单邮件测试
*/
public void sendMail(User user) {
setSMTPInfo(user);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
try {
helper.setFrom(mailSender.getUsername());
// 或new String[]{"xxx"}
helper.setTo("xxx");
helper.setSubject("测试邮件");
helper.setText("测试邮件内容");
} catch (MessagingException e) {
e.printStackTrace();
}
mailSender.send(mimeMessage);
}
@Value("${prop.file}")
private String propfileName; // 读取配置文件
public void setSMTPInfo(User user){
Resource propertiesFile = new ClassPathResource(propfileName);
Properties fileProp = new Properties();
try {
File outfile = propertiesFile.getFile();
fileProp.load(new FileInputStream(outfile));
if (StringUtils.isNotBlank(user.getEmail())
&& StringUtils.isNotBlank(user.getEmailPassword())){
mailSender.setUsername(user.getEmail());
fileProp.setProperty("spring.mail.username", user.getEmail());
mailSender.setPassword(EnOrDecryptionUtil.base64Decrypt(user.getEmailPassword()));
fileProp.setProperty("spring.mail.password", EnOrDecryptionUtil.base64Decrypt(user.getEmailPassword()));
OutputStream fos = new FileOutputStream(outfile);
fileProp.store(fos, "file updated on" + new Date());
}
} catch (IOException e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
log.info("已成功设置邮件发送服务器!");
}
上面SpringBoot 使用的方法和SpringMVC其实是一致的,所以在SpringBoot配置那要将更改的信息和不更改的信息分开,否则使用该方法后,再次启动项目会报错,除非启动前mvn clean或者rebuild。因编译后的配置文件中被更改的信息模式会被更改为properties格式,不能正常使用。
2.
设置一个公共替换发件人设置的方法setSMTPInfo(sysUser),每次调用发送邮件方法时调用该功能方法。因发送邮箱后缀是一样的,所以不需要重新设置主机、端口号、协议。
// import org.springframework.mail.javamail.JavaMailSenderImpl;
@Autowired
private JavaMailSenderImpl mailSender;
public void setSMTPInfo(User user){
if (StringUtils.isNotBlank(user.getEmail())
&& StringUtils.isNotBlank(user.getEmailPassword())) {
mailSender.setUsername(user.getEmail());
mailSender.setPassword(EnOrDecryptionUtil.base64Decrypt(user.getEmailPassword()));
log.info("已成功设置邮件发送服务器!");
}else{
mailSender.setUsername("xxx");
mailSender.setPassword(EnOrDecryptionUtil.base64Decrypt("xxx"));
log.info("登录人邮箱或者密码为空,默认xxx为发送人!");
}
}
注:项目重新发布后,配置文件还是原有的配置信息,不为更改后的;
邮箱参数含义
| 参数 | 类型 | 解释 |
|---|---|---|
| mail.smtp.connectiontimeout | int | Socket connection timeout value in milliseconds. This timeout is implemented by java.net.Socket. Default is infinite timeout. |
| mail.smtp.timeout | int | Socket read timeout value in milliseconds. This timeout is implemented by java.net.Socket. Default is infinite timeout. |
| mail.smtp.writetimeout | int | Socket write timeout value in milliseconds. This timeout is implemented by using a java.util.concurrent.ScheduledExecutorService per connection that schedules a thread to close the socket if the timeout expires. Thus, the overhead of using this timeout is one thread per connection. Default is infinite timeout. |
因为上面几个配置```连接时间限制、邮件接收时间限制、邮件接收时间限制```默认时间为无穷大,所以若不配置,则邮箱发送的等待时间可能是无穷大,出现异常后(比如邮箱服务器繁忙)客户端有可能永远在等待往服务器读写消息。这里涉及到跟服务器间的socket交互。*如下图,JavaMail在socket读写过程中有可能无限等待下去


本文介绍了如何在运行时动态更改SpringMVC和SpringBoot应用的配置文件,特别是邮件发送人的设置。强调了在SpringBoot中需要将可变和不可变配置分开,以避免重启时的错误。并提供了一个公共方法来替代发件人设置,确保邮件发送的正确性。需要注意的是,重新部署项目后,配置文件将恢复为原始内容。
383

被折叠的 条评论
为什么被折叠?



