使用Spring提供的mail API来发送邮件

Java中有mail的技术。使用Spring的mail可以简化代码


上Spring mail API的demo代码,代码上的注释足以说明一切,实际上这是一个十分简单的技术。。。。


package org.mail.test;

import java.io.File;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SpringMail
{
	
	private static String host = "smtp.qq.com";

	//目的邮箱  写上自己要发送的邮箱地址
	private static String to = "";

	//发送邮箱  写上自己要发送的邮箱地址....
	private static String from = "";

	//用户名
	private static String username = "";

	//密码
	private static String password = "";

	//邮件主题
	private static String subject = "测试邮件主题...";
	
	
	private static Properties prop = new Properties();

	static
	{
		prop.put(" mail.smtp.auth ", "false"); 
		prop.put(" mail.smtp.timeout ", " 25000 ");
		prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		prop.put("mail.smtp.port", 465);
	}
	

	public static void main(String[] args) throws Exception
	{
		JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
		
		MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
		
		javaMailSenderImpl.setHost(host);
		javaMailSenderImpl.setUsername(username);
		javaMailSenderImpl.setPassword(password);

		
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
		
		mimeMessageHelper.setFrom(from);
		mimeMessageHelper.setSubject(subject);
		mimeMessageHelper.setText("",true);
		mimeMessageHelper.setTo(to);
		mimeMessageHelper.addAttachment("hello.jpg",new FileSystemResource(new File("C:/Users/Administrator/Desktop/icon.JPG")));
		
		javaMailSenderImpl.setJavaMailProperties(prop);
		
		javaMailSenderImpl.send(mimeMessage);
		System.out.println("send message ok .....");
	
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值