前言:最近在阅读《Spring实战》(第四版)这本书,正好公司项目里有发送邮件的模块,看了看源码,发现Spring有更加简洁的配置和使用方式,特此记录,仅供参考。
1.System.getProperty()和System.getenv()的使用
System.getenv()方法可以返回当前系统的环境变量,如下
{configsetroot=C:\WINDOWS\ConfigSetRoot, USERDOMAIN_ROAMINGPROFILE=LAPTOP-5JT2BFFK, LOCALAPPDATA=C:\Users\fspirit\AppData\Local, PROCESSOR_LEVEL=6, VS140COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\, USERDOMAIN=LAPTOP-5JT2BFFK, LOGONSERVER=\\LAPTOP-5JT2BFFK, JAVA_HOME=C:\IT\jdk, SESSIONNAME=Console, ALLUSERSPROFILE=C:\ProgramData, PROCESSOR_ARCHITECTURE=AMD64, PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules, SystemDrive=C:, CATALINA_BASE=C:\IT\Tomcat\apache-tomcat-7.0.72-windows-x64\apache-tomcat-7.0.72, MAVEN_HOME=C:\IT\maven\maven3, OneDrive=C:\Users\fspirit\OneDrive, APPDATA=C:\Users\fspirit\AppData\Roaming, USERNAME=fspirit, ProgramFiles(x86)=C:\Program Files (x86), AWE_DIR=C:\Softwares\MarkdownPadAddition\1.6.6\, VBOX_MSI_INSTALL_PATH=C:\Program Files\Oracle\VirtualBox\, CommonProgramFiles=C:\Program Files\Common Files, Path=C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\IT\jdk\bin;C:\IT\mysql\bin;C:\IT\jdk\jre\bin;C:\IT\Tomcat\apache-tomcat-7.0.72-windows-x64\apache-tomcat-7.0.72\lib;C:\IT\Tomcat\apache-tomcat-7.0.72-windows-x64\apache-tomcat-7.0.72\bin;C:\IT\maven\maven3\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Users\fspirit\AppData\Local\Programs\Python\Python36\Scripts;C:\Users\fspirit\AppData\Local\Programs\Python\Python36\Scripts\;C:\Users\fspirit\AppData\Local\Programs\Python\Python36\;C:\Users\fspirit\AppData\Local\Microsoft\WindowsApps;, PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC, OS=Windows_NT, test=xixixiix, COMPUTERNAME=LAPTOP-5JT2BFFK, CATALINA_HOME=C:\IT\Tomcat\apache-tomcat-7.0.72-windows-x64\apache-tomcat-7.0.72, PROCESSOR_REVISION=4e03, CLASSPATH=.;C:\IT\jdk\lib;C:\IT\jdk\lib\tools.jar, CommonProgramW6432=C:\Program Files\Common Files, ComSpec=C:\WINDOWS\system32\cmd.exe, ProgramData=C:\ProgramData, ProgramW6432=C:\Program Files, HOMEPATH=\Users\fspirit, SystemRoot=C:\WINDOWS, TEMP=C:\Users\fspirit\AppData\Local\Temp, MYSQL_HOME=C:\IT\mysql, HOMEDRIVE=C:, PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 78 Stepping 3, GenuineIntel, USERPROFILE=C:\Users\fspirit, TMP=C:\Users\fspirit\AppData\Local\Temp, CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files, ProgramFiles=C:\Program Files, PUBLIC=C:\Users\Public, NUMBER_OF_PROCESSORS=4, windir=C:\WINDOWS}
上述配置是我的本地机器的环境变量,是在Windows系统下的,可以在系统设置中添加环境变量,然后通过System.getenv("")方法获取,例如获得自己设置的java环境变量
System.getenv("JAVA_HOME")
输出为 C:\IT\jdk
当然这里可以自己设置,在IDEA中也可以在Edit Configurations中设置
<img src="https://img.haomeiwen.com/i5834071/e1c08435bbb978ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "200" height = "200" alt="IDEA的设置" align=center />
<img src="https://img.haomeiwen.com/i5834071/7d1fe90c45a512c1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "200" height = "200" alt="IDEA中设置" align=center />
设置完成后,即可使用上述代码获取。System.getenv()是针对当前操作系统的
System.getProperty("") 则是对当前进程有效,即该JVM所在进程
System.setProperty("test","hello")
System.getProperty("test") 获取hello
下面的写法也很通用
Properties prop = System.getProperties();
prop.setProperty("test","hello");
System.out.println(prop.get("test"));
同样的,可以在IDEA直接设置,然后在代码中获取,在前面图中的VM options中设置即可,这里就不贴图啦
一般项目中常用的方式是使用配置文件,例如数据库的信息,存放在文件中,直接获取
System.getProperties().load(new FileReader("config.txt"));
在项目根目录下创建config.txt文件,里面填上需要的键值对即可,可以使用同样的getProperty(String name)获取
hello=world
great=code
下面进入如何发送邮件,Spring集成了Mail发送,在org.framework.spring-support里org.framwork.spring.mail里有Mailsender以及Mailsender的实现类,直接引用即可。
@Bean
MailSender mailSender(){
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.qiye.163.com");
mailSender.setPort(25);
mailSender.setUsername("***@***.com");
mailSender.setPassword("*********");
return mailSender;
}
配置bean后,直接写实现类即可
@Component
public class TestMail extends AbstractBaseAction{
@Autowired
MailSender mailSender;
@Override
public void run() throws ActionException {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("autopost@zuihuibao.com");
message.setTo("fanqingyuan@zuihuibao.com");
message.setSubject("test");
message.setText("test...");
mailSender.send(message);
}
}
在main方法中调用即可
public class MainTask {
private static final Logger logger = LoggerFactory.getLogger(MainTask.class);
public static void main(String[] args) {
try {
String actionName = args[0];
List<String> otherParamList = Arrays.asList(args).subList(1, args.length);
logger.info("--------------begin to exec method:[ " + actionName + " ]--------------");
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("production");
ctx.scan("com.fqy.java.report");
ctx.refresh();
AbstractBaseAction action = ctx.getBean(actionName, AbstractBaseAction.class);
action.setParams(otherParamList);
action.run();
logger.info("--------------end to exec method:[ " + actionName + " ]--------------");
} catch (Exception e) {
logger.error("Exception:", e);
System.exit(1);
}
}
}
运行即可发送文件~很简单
后面会写如何使用Springboot配置,以及如何使用thymeleaf模板。
Spring-boot搭建项目发送邮件
首先,使用Spring-boot搭建一个web项目,众所周知,Spring-boot搭建web项目可以省去很多基本配置,它集成了SpringMVC的基本的包,以及tomcat的配置,非常方便。直接在ide中运行main函数即可
首先创建Spring-boot项目,在idea中选择,newproject-Spring-Initializr-next 在基本配置中选择 web,session,mysql等,记得选择IO中的mail,这个包中有Spring集成的邮件发送模块,否则需要在pom.xml文件中手动写入
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>
搭建后可以写个controller 运行,不过会有很多bug
例如会报错spring.session.store-type读不到,可以通过在application.properties中设置
spring.session.store-type=none
如果没连数据库,会报database相关的错,可以在主函数中不加载相关Bean即可
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class TestmailApplication {
public static void main(String[] args) {
SpringApplication.run(TestmailApplication.class, args);
}
}
基本上进行上述配置就OK了,写一个controller,运行main函数,打开浏览器,输入http://localhost:8080/send/mail 即可
@RestController
@RequestMapping("/send")
public class MailSenderControler {
@RequestMapping("/mail")
public String index() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.qiye.163.com");
mailSender.setPort(25);
mailSender.setUsername("****@gaga.com");
mailSender.setPassword("asfasf11312dsf");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("****@gaga.com");
message.setTo("fspirit@yeah.net");
message.setText("This is a test e-mail");
mailSender.send(message);
return "success";
}
}
在普通Spring项目中发送邮件
首先创建个普通的Springmaven项目,在pom.xml文件中添加相关依赖包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
和在Spring-boot中类似,只不过改为写一个基类和一个mian方法,执行后同样是可以的
public static void main( String[] args )
{
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.fqy");
ctx.refresh();
AbstractAction action = ctx.getBean("testMailSender", AbstractAction.class);
action.go();
}
主要的两个包是javax.mail和org.springframework的spring-context-support类
网友评论