发送邮件

首先导入使用jar包:activation.jar,commons-logging-1.0.4.jar,mail.jar,spring.jar


applicationContext.xml的配置  用于连接邮件服务器

	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host">
			<value>smtp.zz.com</value>
		</property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
				<prop key="mail.smtp.timeout">25000</prop>
			</props>
		</property>
		<property name="username">
			<value>[email protected]</value>
		</property>
		<property name="password">
			<value>123456</value>
		</property>
	</bean>




package com.test;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class TestMail {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "spring/applicationContext.xml" });
		// 一般格式
		JavaMailSender javaMailSender = (JavaMailSender) context
				.getBean("mailSender");
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

		simpleMailMessage.setFrom("[email protected]");
		simpleMailMessage.setTo("[email protected]");
		simpleMailMessage.setSubject("test");
		simpleMailMessage.setText("haha  this is test");

		// javaMailSender.send(simpleMailMessage);

		// HTML格式

		JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
		MimeMessage mailMessage = senderImpl.createMimeMessage();
		// 设置utf-8或GBK编码,否则邮件会有乱码
		MimeMessageHelper messageHelper = null;
		try {
			messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
		} catch (MessagingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			messageHelper.setTo("[email protected]");// 接受者
			messageHelper.setFrom("[email protected]");// 发送者
			messageHelper.setSubject("测试邮件");// 主题
			// 邮件内容,注意加参数true,表示启用html格式
			messageHelper
					.setText(
							"<html><head></head><body><h1>hello!!test</h1></body></html>",
							true);

			messageHelper.addInline("b", new File("E:/temp/11.jpeg"));
//			File file = new File("E:/测试中文文件.rar");
			// 这里的方法调用和插入图片是不同的,使用MimeUtility.encodeWord()来解决附件名称的中文问题
//			messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()),
//					file);
			javaMailSender.send(mailMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}


你可能感兴趣的:(发送邮件)