五、发送带附件的邮件
发送带附件的邮件和发送内嵌的邮件相似,都是multipart类型的邮件。在src下存放两个文件:"2.jpg"和"文档.doc"。注意当附件名为中文时,会出现乱码,此时需用MimeUtility.encodeWord()方法对文件名进行编码:
public void sendAttachmentEmail(JavaMailSender sender) throws MessagingException{
MimeMessage msg=sender.createMimeMessage();
//创建MimeMessageHelper实例,第2个参数表示是否为multipart邮件,第3个参数表示MimeMessage的编码
MimeMessageHelper helper=new MimeMessageHelper(msg,true,"utf8");//true表示为multipart邮件
helper.setFrom("dongkk@sina.com");
helper.setTo("dongkk@sina.com");
helper.setSubject("注册成功-带附件");
helper.setText("欢迎访问www.sina.com.cn");
try {
ClassPathResource file1=new ClassPathResource("2.jpg");
helper.addAttachment("2.jpg",file1.getFile());
ClassPathResource file2=new ClassPathResource("文档.doc");
helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
//当附件的文件名带有中文时,会出现乱码。所以需对文件名进行编码转换,可使用
//javax.mail.internet.MimeUtility.encodeWord(String filename)
//如果主题出现乱码,可以使用该函数,也可以使用下面的函数
//helper.setSubject(MimeUtility.encodeText(String text,String charset,String encoding))
//第2个参数表示字符集,第三个为目标编码格式。
//MimeUtility.encodeWord(String word,String charset,String encoding)
} catch (IOException e) {
e.printStackTrace();
}
sender.send(msg);
System.out.println("成功发送带附件邮件!");
}
此时,附件能正常显示中文名。关于Spring中发送邮件的乱码问题可参考http://blog.csdn.net/matrixjava/archive/2008/11/06/3237772.aspx。其介绍了3种常遇到的问题:
1.增加验证,否则会报:553 authentication is required 的错误信息
Properties prop = new Properties();
prop.setProperty("mail.smtp.auth", "true");
JavaMailSenderImpl.setJavaMailProperties(prop);
2.当邮件内容是HTML语言时的中文问题:
初始化MimeMessageHelper辅助类时,设置"GBK" encoding!如:
MimeMessageHelper messageHelp = new MimeMessageHelper(message,true,"GBK");
同时在设置:<META http-equiv=Content-Type content='text/html; charset=GBK'>
如果都设置为"UTF-8",在某些邮件客户端标题不能正常显示!
3.邮件附件的中文问题!
spring的文档里面说MimeMessageHelper设置了encoding,同时对title,text,attach产生作用,但还是会出问题:解决方法:MimeUtility.encodeWord(file.getName());就OK了!
分享到:
相关推荐
java 发送邮件 spring发送邮件Mail
利用spring下的一个类进行邮件发送,内附具体用法
Spring实现各种邮件的发送 简单配置就可发送邮件
用spring发送邮件,该功能在一般系统监控中经常用到。
(二)本项目中主要以发送 HTML 格式邮件为例,发送邮件并把邮箱保存到数据库中 FreeMarker模板引擎 Spring Boot整合邮件发送并保存历史发送邮箱 邮件模板 Spring Boot整合邮件发送并保存历史发送邮箱 运行环境...
spring发送邮件所需jar包
Spring整合Quartz定时发送邮件
spring+velocity发送邮件,spring+velocity发送邮件
Spring mail发送邮件实例 Spring mail发送邮件实例
Spring 封装的JavaMail,使邮件发送变的相当简单,我通过Spring的邮件发送实现了发纯文本形的内容,HTMl,带附件,带图片等示例代码,并自行测试过.希望对初学者有帮助
它包括了发送电子邮件的主要接口MailSender,和值对象SimpleMailMessage,它封装了简单邮件的属性如from, to,cc, subject,text。 包里还包含一棵以MailException为根的checked Exception继承树,它们提供了对底层...
用spring实现了定时发送邮件,无需复杂的代码
基于spring mvc 框架,用freemarker创建邮件模板,包括详细邮件发送功能的spring配置和实现代码
使用springmvc 调用.JavaMailSenderImpl 发送邮件
使用Spring Boot 开发支持多附件邮件发送微服务平台代码
使用Spring mail发送邮件的完整实例,包含代码与Spring mail的jar,可直接运行与使用。相关学习文档参考博客《Spring Mail邮件发送 http://blog.csdn.net/chenxiang0207/article/details/8256528》。
Spring邮件发送服务(java邮件发送),支持多附件、多人发送/抄送/暗送
包含了spring发送邮件的说明文档和代码案例以及图解。
pdf介绍spring-boot-邮件发送。 Spring Boot通过集成spring-boot-starter-mail依赖...发送邮件:在需要发送邮件的地方调用邮件发送服务,传入邮件信息对象,即可完成邮件的发送。 测试邮件发送:运行应用程序并触发邮件