多平台统一管理软件接口,如何实现多平台统一管理软件接口
242
2023-07-20
Java的Spring框架中实现发送邮件功能的核心代码示例
Spring中已经封装了邮件操作类,通过spring配置文件可以便捷地注入到controller、action等地方。
下面是配置:
p:host="${mail.host}" p:port="${mail.port}" p:username="${mail.user}" p:password="${mail.passwd}">
p:host="${mail.host}" p:port="${mail.port}"
p:username="${mail.user}" p:password="${mail.passwd}">
mail配置
Email Configuration:
mail.host=smtp.163.com
mail.port=25
mail.user=xxxxxx@163.com
mail.passwd=xxxxxxxx
mail.from=xxxxxx@163.com
控制器中注入mailSender:
@Controller
public class EmailController {
private MailSender mailSender;
@Value("${mail.from}")
String emailFrom;
@Autowired
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
@RequestMapping(value="/sendEmail",method=RequestMethod.POST)
public ModelAndView sendhttp://Email(@ModelAttribute("newEmail") ContactEmail newEmail,
BindingResult bindResult,SessionStatus status){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(newEmail.getTo());
message.setFrom(emailFrom);
message.setSubject(newEmail.getSubject());
message.setText(newEmail.getContent());
String result = "";
try{
mailSender.send(message);
result = "Email was sent!";
}KkRoZKhcatch(MailException e){
result = "Sending email failed!
}
ModelAndView view = new ModelAndView("emailResult");
view.addObject("result", result);
return view;
}
}
mail form:
to:
subject:
content:
发送带附件的邮件:
try{
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
senderImpl.setHost("smtp.163.com");
senderImpl.setUsername("zhangfl85");
senderImpl.setPassword("851010");
senderImpl.setJavaMailProperties(props);
MimeMessage mimeMessge = senderImpl.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessge,true);
mimeMessageHelper.setTo("zhangfl85@126.com");
mimeMessageHelper.setFrom("zhangfl85@163.com");
mimeMessageHelper.setSubject("添加附件测试");
mimeMessageHelper.setText("test",true); FileSystemResource img = new FileSystemResource(new File("I:/liang.jpg"));
mimeMessageHelper.addAttachment(MimeUtility.encodeWord("3M样品仓库标准送货单模板.jpg"),
,img);
senderImpl.send(mimeMessge);
}catch(Exception e){
e.printStackTrace();
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~