1.通常情况下使用JavaMail原始API进行邮件发送的代码示例
String host = "your.mail.host";
String username = "...";
String password = "...";
String protocal = "smtp";
String mailSubject = "邮件标题";
String mailContext = "邮件内容";
String mailEncoding = "UTF-8";
boolean plainTextMail = false; //是否发送普通文本文件
Properties props = new Properties();
props.put("mail.smtp.auth","true");
Transport transport = null;
try{
Session session = Session.getDefaultInstance(props,null);
MimeMessage message = new MimeMessage(session);
message.setRecipients(RecipientType.TO,new Address[]{new InternetAddress([email protected])});
message.setRecipient(RecipientType.CC,new InternetAddress([email protected]));
message.setFrom(new InternetAddress([email protected]));
message.setSubject(mailSubject,mailEncoding);
if(plainTextMail){
message.setText(mailContext,mailEncoding);
}else{
Multipart multipart= new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(mailContext);
multiPart.addBodyPart(bodyPart);
bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("attachment.name"); //添加附件
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
multiPart.addBodyPart(bodyPart);
message.setContent(multiPart);
}
transport = session.getTransport(protocal);
transport.connect(host,username,password);
transport.sendMessage(message,message.getAllRecipients());
}catch(Exception e){
//根据情况处理异常
}finally{
if(transport != null){
try{
transport.close();
}catch(MessagingException e){
e.printStackTrace();
}
}
}
使用JavaMail API发送邮件,我们需要设置JavaMail的Session需要的某些属性,然后根据Session构建相应的MimeMessage实例,并在构建完的MimeMessage实例上设置将要发送的消息的方方面面。在消息准备完成后,我们才通过Transport连接到邮件服务器,并发送准备好的邮件信息,还不要忘了异常的处理和Transport的关闭
2.Spring的E-mail抽象层分析
Spring所提供的E-mail抽象层主要体现在两个层次,即MailMessage抽象层次和MailSender抽象层次
<<Interface>>
MailMessage--------SimpleMailMessage,MimeMailMessage
<<Interface>>
MailSender---------CosMailSenderImpl,<<Interface>>JavaMailSender---------JavaMailSenderImpl
MailMessage抽象层次在于对要发送的邮件信息进行抽象和建模,MailMessage作为该层次的统领,定义了一套标准的邮件信息操作方式
MailMessage主要有两个实现类,SimpleMailMessage代表了普通的文本邮件(plain text mail),而MimeMailMessage则代表能够发送更丰富内容的MIME(Multipart Internet Message Encoding)类型的信息
mailMessage.setTo(...);
mailMessage.setCc(...);
mailMessage.setBcc(...);
...
MailSender抽象接口的主要目的即使屏蔽调各种E-mail解决方案的差异性,不管底层的E-mail解决方案如何变换,只需要把使用这些E-mail解决方案实现的MailSender实现类注入给依赖MailSender接口的对象即可
public interface MailSender{
void send(SimpleMailMessage simpleMessage) throws MailException;
void send(SimpleMailMessage[] simpleMessages) throws MailException;
}
JavaMailSender扩展自MailSender,在MailSender发送普通文本文件的基础上,添加了发送MIME邮件的功能。JavaMailSenderImpl封装JavaMail API使用的方法是模板方法模式
JavaMailSenderImpl实现类相关模板方法代码摘录
public void doSend(MimeMessage[] message2Send){
//预处理
Transport transport = getTransport(getSession());
transport.connect(getHost(),getPort(),getUsername(),getPassword());
try{
for(int i = 0; i < mimeMessages.length; i++){
MimeMessage mimeMessage = mimeMessages[i];
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
}
}finally{
transport.close();
}
}
3.JavaMailSender提供了两种常用的邮件发送方式,一种是直接外部创建要发送的MailMessage实例,然后传给JavaMailSender发送;另一个则是使用JavaMailSender公开给我们的MimeMessagePreparator回调接口
1)直接创建邮件消息并发送
JavaMailSender mailSender = new JavaMailSenerImpl();
JavaMialSenderImpl javaMailSender = (JavaMailSenderImpl)mailSender;
javaMailSender.setHost("...");
javaMailSender.setUseranme("...");
javaMailSender.setPassword("...");
Properties javaMailProps = new Properties();
javaMailProps.put("mail.smtp.auth","true");
javaMailSender.setJavaMailProperties(javaMailProps);
//mailSender现在可以使用
JavaMailSenderImpl配置代码示例
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="...">
<property name="username" value="...">
<property name="password" value="...">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
因为JavaMail的MimeMessage不能独立于Session而创建,所以只有在有了可用的JavaMailSender之后,才能开始创建要发送的邮件信息,要通过JavaMailSender的createMimeMessage()方法达成
MimeMessage javaMailMessage = mailSender.createMimeMessage();
MimeMailMessage messageWrapper = new MimeMailMessage(javaMailMessage);
messageWrapper.setTo("...");
messageWrapper.setFrom("...");
messageWrapper.setSubject("...");
messageWrapper.setText("...");
//其他设定...
mailSender.send(messageWrapper.getMimeMessage());
Spring提供的MimeMailMessage对createMimeMessage()返回的MimeMessage做了简单的包装
4.使用MimeMessagePreparator发送邮件
JavaMailSender还提供了使用MimeMessagePreparator回调接口的邮件发送方法。MimeMessagePreparator作为回调接口,可以获得JavaMailSender公开给它的MimeMessage实例
沿用已经设定完毕的JavaMailSender实例
mailSender.send(new MimeMessagePreparator(){
public void prepare(MimeMessage message) throws Exception{
MimeMailMessage messageWrapper = new MimeMailMessage(message);
messageWrapper.setTo("...");
messageWrapper.setFrom("...");
messageWrapper.setSubject("...");
messageWrapper.setText("...");
}
} );
MimeMessageHelper可以帮助我们完成更加丰富的邮件内容设定
MimeMessageHelper使用代码示例
mailSender.send(new MimeMessagePreparator(){
public void prepare(MimeMessage message) throws Exception{
MimeMessageHelper messageHelper = new MimeMessageHelper(message,true,"UTF-8");
messageHelper.setFrom("...");
messageHelper.setTo("...");
messageHelper.setSubject("...");
StringBuilder builder = new StringBuilder("");
builder.append("<html><head><meta http-equiv='ContentType' content='text/html;charset=utf-8'></head><body><pre>");
builder.append("<img src='cid:inlinePic'>");
builder.append("</pre></body></html>");
messageHelper.setText(builder.toString(),true);
messageHelper.addInline("inlinePic",new ClassPathResource("img/picture.gif"));
messageHelper.addAttachment("fileName.pdf",new ClassPathResource("yourFile.pdf"));
}
});
JavaMailSender结合MimeMessagePreparator和MimeMessageHelper的组合,是使用JavaMailSender发送邮件的最常用方式