Spring发送邮件如何内嵌图片增加附件
作者:cuisuqiang
这篇文章主要介绍了Spring发送邮件如何内嵌图片增加附件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
用到的JAR包:
spring.jar
mail.jar
activation.jar
commons-logging.jar
log4j-1.2.15.jar
内嵌图片,给定一个CID值即可,增加附件,使用MimeMessageHelper的addAttachment即可
现在一般不会做内嵌图片,因为这样邮件会很大,容易对服务器造成压力,一般做法是使用图片链接
另外,如果要做内嵌或发送图片,你应该使用信用较高的邮箱帐户,否则会报错:
554 DT:SPM 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件
对于163邮箱服务器会产生的其他问题,参见:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html
以下是示例代码:
package test;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
* 这里不做异常处理
*/
public class SendMail {
public static void main(String[] args) throws Exception{
// 发送器
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("smtp.163.com");
sender.setPort(25); // 默认就是25
sender.setUsername("用户@163.com");
sender.setPassword("密码");
sender.setDefaultEncoding("UTF-8");
// 配置文件对象
Properties props = new Properties();
props.put("mail.smtp.auth", "true"); // 是否进行验证
Session session = Session.getInstance(props);
sender.setSession(session); // 为发送器指定会话
MimeMessage mail = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
helper.setTo("用户@163.com"); // 发送给谁
helper.setSubject("强哥邀请,谁敢不从!"); // 标题
helper.setFrom("用户@163.com"); // 来自
// 邮件内容,第二个参数指定发送的是HTML格式
helper.setText("<font color='red'>强哥邀请你访问我的博客:http://cuisuqiang.iteye.com/!</font><br><img src='cid:myImg'>",true);
// 增加CID内容
ClassPathResource img = new ClassPathResource("abc.jpg");
helper.addInline("myImg", img);
// 增加附件
ClassPathResource file = new ClassPathResource("abc.zip");
helper.addAttachment("abc.zip", file);
sender.send(mail); // 发送
System.out.println("邮件发送成功");
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
