我希望我的应用程序能够按需发送电子邮件。我目前正在使用www.mykong.com中的教程,该教程详细介绍了如何设置Gmail设置。
但是,我无法将配置设置放入带注释的弹簧控制器中:我想避免使用以下内容:
ApplicationContext context = new FileSystemXmlApplicationContext(email-context.xml");
MailMail mm = (MailMail) context.getBean("mailMail");
mm.send(message);
从我的调查来看,这似乎相当不受欢迎。我尝试了几件事,但他们似乎都没有找到正确的bean并产生nullpointerexception。有没有办法可以将它添加到任何必要的控制器,例如@Property(mailMail)
或@Autowired private mailMail
?或者我应该将设置从我的电子邮件上下文移动到java本身?
我的文件如下:
EmailSender.java
public class EmailSender {
@Autowired
private MailSender mailSender;
public void sendMail(String subject, String msg) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("beesden@*.com");
message.setTo("beesden@*.com");
message.setSubject(subject);
message.setText(msg);
mailSender.send(message);
}
}
的PageController
@RequestMapping(value = { "/{name}" }, method = RequestMethod.GET)
public String showPage(@PathVariable("name") String name, HttpServletRequest request, Model model) {
logger.debug("Page request: " + name);
mm.sendMail("Hi","Test");
return "webpage";
}
电子邮件-context.xml中
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="toby@gmail.com" />
<property name="password" value="tobytobytoby" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="mailMail" class="org.system.EmailSender">
<property name="mailSender" ref="mailSender" />
</bean>
(注意我在这里更改了用户名和密码,它们在系统中是正确的......)
非常感谢