最近 有做 mail 发送相关内容,做个 简单整理
用的 是 spring 的mail 发送,主要 依赖几个类:
org.springframework.mail.javamail.JavaMailSenderImpl;
javax.mail.internet.MimeMessage;
org.springframework.mail.javamail.MimeMessageHelper;
主要是 html模板的发送 :
JavaMailSenderImpl 的实例化可以交给spring 容器管理,主要需要提供的几个属性:
username、password、host
部分邮箱的 发送还需加入 port
设置 javaMailProperties () mail.smtp.auth = true对应 基本的属性
基本的操作代码:
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setXX();
MimeMessage message = sender .createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
helper 需要设置的几个属性
to(发送至的对象、可以多个)、subject(邮件标题)、from(发送邮件的邮箱)、text(邮件内容)
text(“”,boolean x) x为html 页面开关
sender.send(message);完成发送 简单处理完成
遇到问题:
中间有碰到问题夹带图片,但是说不提供图片服务器,不能直接在html中夹带 图片地址
spring 有提供相关的方法:
有用到 spring的类 org.springframework.core.io.Resource(接口)
常用的实现类有
org.springframework.core.io.FileSystemResource;(做测试的时候有用到)
实例化方法 new FileSystemResource(new File(""))(用到的)
org.springframework.core.io.ByteArrayResource;(实际使用)
实例化方法 new ByteArrayResource(byte[])
应为获取不到文件的物理路径,只能用它的网路路径写成流转化为byte[]
使用了 commons.io 里面的一个类 IOUtils
有用到如下方法
:
List<Rescource> resources = new Arraylist<Rescource>();
URL url = new URL(im);
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
resources.add(new ByteArrayResource(IOUtils.toByteArray(in)){
public String getFilename() {
return "aa";
}
});
记得要重写 接口的 getFilename()方法把它识别为文件,不然报错
helper.addInline(Resource resource)(这个方法要放在setText()之后)
还有添加附件方法 addAttachement('')添加附件(暂时没有使用过)
发送邮件成功后那些展示的图片实际上是在邮件里面写入了若干个 .bin文件,在读取邮件的时候把那些图片写出来
测试 qq.163 邮箱能正常读出,hotmail把图片文件读出时间较长(也可能是图片过大,原因不详)
gmail邮箱 好像不接收样式?html的样式没有展示出来
还有 内容待整理