Java中发送邮件的方法之一,需要用到spring框架集成的JavaMailSenderImpl、SimpleMailMessage两个实现类。
一,创建一个service,代码如下:
public interface MailService { public Boolean sendTextMail(String subject,String text,String to); public Boolean sendHtmlMail(String subject,String text,String to); }
二,service实现类如下:
@Service public class MailServiceImpl implements MailService{ @Autowired private JavaMailSenderImpl mailSender; @Autowired private SimpleMailMessage mailMessage; @Override public Boolean sendTextMail(String subject,String text,String to) { //发送文本邮件,纯文字。 try { mailMessage.setSubject(subject); mailMessage.setText(text); mailMessage.setTo(to); mailSender.send(mailMessage); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public Boolean sendHtmlMail(File file, String subject, String text, String to) { //发送HTML邮件,包含格式、图片、附件等 try { MimeMessage mimeMessage =mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true); String from = ApplicationUtils.getApplicationSettings().getProperty("mail.from","xx@sina.com"); //这里的发送者是从配置文件中读取的。 messageHelper.setFrom(from); messageHelper.setSubject(subject); messageHelper.setTo(to); messageHelper.setText("<html><head></head><body>"+text+"</body></html>", true); //发送图片 /* FileSystemResource image = new FileSystemResource(new File("C:\text.png")); //添加图片 messageHelper.addInline("img", image);*/ messageHelper.addAttachment(file.getName(), file); //添加附件 mailSender.send(mimeMessage); return true; } catch (MessagingException e) { e.printStackTrace(); } return false; } }