Spring 使用163发邮件带附件

图示:
Spring 使用163发邮件带附件_第1张图片

 

Mail 有附件的邮件

package cn.mail;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
 * 有附件的邮件
 * */
public class Mail {
	private JavaMailSender mailSender;//必须使用 JavaMailSende,是  MailSender 子接口
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	//发送
	public void send(){
		//建立有附件的邮件对象
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		try {
			//对象,是否多部分,编码
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GBK");
			helper.setFrom("[email protected]");
			helper.setTo("[email protected]");
			helper.setSubject("Spring 简单邮件带附件");
			helper.setText("元旦快乐");
			//添加附件 1
			ClassPathResource file1 = new ClassPathResource("image.JPG");
			//把附件加到邮件中:附件文件名,文件对象
			helper.addAttachment(file1.getFilename(), file1.getFile());
			//添加附件 2:附近的文件名为中文时,需要对文件名进行编码转换,解决乱码问题
			ClassPathResource file2 = new ClassPathResource("文档.docx");
			//附件的文件名有汉字
			helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()), file2.getFile());
			mailSender.send(mimeMessage);
			System.out.println("发送成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

applicationContext.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
	<!-- Spring 实现的发邮件的类 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="smtp.163.com" /><!-- 服务器 -->
		<property name="port" value="25" /><!-- 端口 -->
		<property name="username" value="[email protected]" /><!-- 用户名 -->
		<property name="password" value="******" /><!-- 密码 -->
		<property name="protocol" value="smtp" /><!-- 协议 -->
		<property name="defaultEncoding" value="utf-8" /><!-- 默认编码 -->
		<property name="javaMailProperties">
			<props>
				<!-- 设置 SMT 服务器需要用户验证  -->
				<prop key="mail.smtp.auth">true</prop>
			</props>
		</property>		
	</bean>
	<!-- 简单邮件发送 -->
	<bean id="mail" class="cn.mail.Mail" p:mailSender-ref="mailSender" />
</beans>

 

Test 测试类

package cn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mail.Mail;
public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		/*测试简单邮件带附件*/
		Mail mail = (Mail) context.getBean("mail");
		mail.send();
	}
}

 

效果图:
Spring 使用163发邮件带附件_第2张图片
 

 

你可能感兴趣的:(spring)