java发送邮件

java发送邮件

项目需要用到发送邮件这个功能,百度一大堆代码,只能看不能用,让人看着很着急,下面简单介绍一下java用qq发送邮件的方法。。
不喜勿喷..
喜欢点赞..

以下代码糅合了百度上面找的大神发的代码,借鉴,谢谢。。

JAVA邮件发送的大致过程是这样的的:

1、构建一个继承自javax.mail.Authenticator的具体类,并重写里面的getPasswordAuthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。

2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。

3、通过构建的properties文件和javax.mail.Authenticator具体类来创建一个javax.mail.Session。Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。

4、构建邮件内容,一般是javax.mail.internet.MimeMessage对象,并指定发送人,收信人,主题,内容等等。

5、使用javax.mail.Transport工具类发送邮件。


下面是通过spring发送邮件的方法

1.首先需要一个不常用的qq做测试,将qq邮箱里面的  POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 开启

步骤: QQ邮箱 --> 邮箱设置 --> 账户 --> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 

图一:
java发送邮件_第1张图片

图二:
java发送邮件_第2张图片

图三:
java发送邮件_第3张图片

图四:
java发送邮件_第4张图片


如此qq邮箱的设计便设置好了,

以下是项目配置了
首先spring的基本jar包和邮件的jar包   -->  mail.jar

项目地址待会儿我放在后面发给大家。。


spring.xml的配置文件:


	
	
		
		
		
		 
		
		
		
		
		
		
		
		
		
		
		
		 
		
			
				true
			
		
	
	
	
		
	

	
		
	

	
		
	

	
		
	
	
	
	
	
	
		
		
	
	


以下是代码编写了。。

1 常规邮件发送
package com.spring.mail.demo1;

import java.util.Date;

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

/**
 * 常规邮件发送
 * @author XiaoLan
 *
 */
public class SimpleMailSender {
	
	private JavaMailSender javaMailSender;

	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}
	
	
	
	public void doSend(){
		//邮件里面的会话对象
		SimpleMailMessage smm = new SimpleMailMessage();
		smm.setFrom("[email protected]"); 	//发件者和配置文件的username保持一致
		smm.setSubject("测试.....");	//主题
		smm.setText("大家好啊!");		//正文
		smm.setTo("[email protected]"); 		//收件者
		smm.setSentDate(new Date());	//发送时间
		javaMailSender.send(smm);
		
	}
	
	public static void main(String[] args) {
		
		new Thread(){
			public void run(){
				
			}
		}.start();
		
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		SimpleMailSender smMailSender = (SimpleMailSender) ac.getBean("simpleMailSender");
		System.out.println("运行!");
		smMailSender.doSend();
	}
	
}

2. 带附件的发送邮件
package com.spring.mail.demo2;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;

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.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.spring.mail.demo1.SimpleMailSender;

/**
 * 带附件的发送邮件
 * @author XiaoLan
 *
 */
public class AttachmentSender {
	
	private JavaMailSender javaMailSender;

	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}
	
	public void doSend() throws MessagingException, UnsupportedEncodingException{
		MimeMessage mm = javaMailSender.createMimeMessage();
		
		//true:表示有附件
		MimeMessageHelper helper = new MimeMessageHelper(mm,true);

		File file1 = new File("attachment/english.txt");
		File file2 = new File("attachment/中文.txt");
		
		//添加附件
		helper.addAttachment(file1.getName(), file1);
		helper.addAttachment(MimeUtility.encodeText(file2.getName()), file2);
		
		//helper设定邮件的其他属性
		helper.setFrom("[email protected]"); 	//发件者和配置文件的username保持一致
		helper.setTo("[email protected]");
		helper.setSubject("有附件没?");
		helper.setText("看一哈有附件!");
		helper.setSentDate(new Date());
		
		javaMailSender.send(mm);
	}

	public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
		
		/*new Thread(){
			public void run(){
				
			}
		}.start();
		*/
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		AttachmentSender amSender = (AttachmentSender) ac.getBean("attachmentSender");
		System.out.println("运行!");
			amSender.doSend();
	}
	
}

3  模板邮件(1)
package com.spring.mail.demo3;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class FreemarkerSender {
	private JavaMailSender javaMailSender;
	private Configuration cfg;
	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}
	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}
	
	public Configuration getCfg() {
		return cfg;
	}
	public void setCfg(Configuration cfg) {
		this.cfg = cfg;
	}
	public void doSend() throws IOException, TemplateException, MessagingException{
		MimeMessage mm = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mm);
		Template template = cfg.getTemplate("template/email.html");
		
		Map map = new HashMap();
		map.put("name", "小飞");
		map.put("when", "下午三点");
		map.put("where", "小区门口");
		
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

		//helper设定邮件的其他属性
		helper.setFrom("[email protected]"); 	//发件者和配置文件的username保持一致
		helper.setTo("[email protected]");
		helper.setSubject("啊啊啊");
		//true:代表网页    
		helper.setText(content,true);
		helper.setSentDate(new Date());
		javaMailSender.send(mm);
	}

	public static void main(String[] args){
		
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		FreemarkerSender sender = (FreemarkerSender) ac.getBean("freemarkerSender");
		
		try {
			sender.doSend();
		} catch (IOException | TemplateException | MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("运行!");
	}
	
}

3  模板邮件(2)
package com.spring.mail.demo3;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;

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

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

/**
 * 模板发送器
 * @author XiaoLan
 *
 */
public class TemplteSender {

	private JavaMailSender javaMailSender;

	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}
	
	public void doSend() throws MessagingException, IOException{
		MimeMessage mm = javaMailSender.createMimeMessage();
		
		//true:表示有附件
		MimeMessageHelper helper = new MimeMessageHelper(mm);

		//利用StringBuilder拼网页
		StringBuilder sb = new StringBuilder();
		BufferedReader br = new BufferedReader(new FileReader("template/email.html"));
		
		while(true){
			String str = br.readLine();
			if (str == null) {
				break;
			}
			sb.append(str);
		}
		
		String content = sb.toString();
		
		//替换占位符的值
		content = content.replaceAll("\\$\\{name\\}", "小飞");
		content = content.replaceAll("\\$\\{when\\}", "下午三点");
		content = content.replaceAll("\\$\\{where\\}", "小区门口");
		
		//helper设定邮件的其他属性
		helper.setFrom("[email protected]"); 	//发件者和配置文件的username保持一致
		helper.setTo("[email protected]");
		helper.setSubject("啊啊啊");
		//true:代表网页    
		helper.setText(content,true);
		helper.setSentDate(new Date());
		javaMailSender.send(mm);
	}
	
	public static void main(String[] args){
		
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		TemplteSender sender = (TemplteSender) ac.getBean("templteSender");
		
		try {
			sender.doSend();
		} catch (MessagingException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("运行!");
	}
}

3.1  模板




天天快递!


	

亲,你的快递到了!

${name} ,在${when}来取您的快递! 地点:${where}

4  邮件的抄送+密送/邮件发送html信息
package com.spring.mail.demo3;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;

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.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 邮件的抄送+密送
 * 
 * 邮件发送html信息
 */
public class HTMLSender {

	private JavaMailSender javaMailSender;

	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public void doSender() throws MessagingException, UnsupportedEncodingException {
		MimeMessage mm = javaMailSender.createMimeMessage();

		// true:表示有附件
		MimeMessageHelper helper = new MimeMessageHelper(mm, true);

		File file1 = new File("attachment/english.txt");
		File file2 = new File("attachment/中文.txt");

		// 添加附件
		helper.addAttachment(file1.getName(), file1);
		helper.addAttachment(MimeUtility.encodeText(file2.getName()), file2);

		// 利用StringBuilder拼网页
		StringBuilder sb = new StringBuilder();
		sb.append("");
		sb.append("

11111线


"); sb.append("神11111线"); // helper设定邮件的其他属性 helper.setFrom("[email protected]"); // 发件者和配置文件的username保持一致 helper.setTo("[email protected]"); //密送 helper.setBcc("[email protected]"); // 抄送 helper.setCc("[email protected]"); helper.setSubject("杀鬼情1111111况网页"); // true:代表网页 helper.setText(sb.toString(), true); helper.setSentDate(new Date()); javaMailSender.send(mm); } public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); HTMLSender sender = (HTMLSender) ac.getBean("htmlSender"); try { sender.doSender(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("运行!"); } }

以上就是spring发送邮件的代码


附上java发送邮件代码:
/**
 * 简单邮件发送器,可单发,群发。
 * 
 */
public class SimpleMailSender {
  
    /**
     * 发送邮件的props文件
     */
    private final transient Properties props = System.getProperties();
    /**
     * 邮件服务器登录验证
     */
    private transient MailAuthenticator authenticator;
  
    /**
     * 邮箱session
     */
    private transient Session session;
  
    /**
     * 初始化邮件发送器
     * 
     * @param smtpHostName
     *                SMTP邮件服务器地址
     * @param username
     *                发送邮件的用户名(地址)
     * @param password
     *                发送邮件的密码
     */
    public SimpleMailSender(final String smtpHostName, final String username,
        final String password) {
    init(username, password, smtpHostName);
    }
  
    /**
     * 初始化邮件发送器
     * 
     * @param username
     *                发送邮件的用户名(地址),并以此解析SMTP服务器地址
     * @param password
     *                发送邮件的密码
     */
    public SimpleMailSender(final String username, final String password) {
    //通过邮箱地址解析出smtp服务器,对大多数邮箱都管用
    final String smtpHostName = "smtp." + username.split("@")[1];
    init(username, password, smtpHostName);
  
    }
  
    /**
     * 初始化
     * 
     * @param username
     *                发送邮件的用户名(地址)
     * @param password
     *                密码
     * @param smtpHostName
     *                SMTP主机地址
     */
    private void init(String username, String password, String smtpHostName) {
    // 初始化props
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", smtpHostName);
    // 验证
    authenticator = new MailAuthenticator(username, password);
    // 创建session
    session = Session.getInstance(props, authenticator);
    }
  
    /**
     * 发送邮件
     * 
     * @param recipient
     *                收件人邮箱地址
     * @param subject
     *                邮件主题
     * @param content
     *                邮件内容
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(String recipient, String subject, Object content)
        throws AddressException, MessagingException {
    // 创建mime类型邮件
    final MimeMessage message = new MimeMessage(session);
    // 设置发信人
    message.setFrom(new InternetAddress(authenticator.getUsername()));
    // 设置收件人
    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    // 设置主题
    message.setSubject(subject);
    // 设置邮件内容
    message.setContent(content.toString(), "text/html;charset=utf-8");
    // 发送
    Transport.send(message);
    }
  
    /**
     * 群发邮件
     * 
     * @param recipients
     *                收件人们
     * @param subject
     *                主题
     * @param content
     *                内容
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(List recipients, String subject, Object content)
        throws AddressException, MessagingException {
    // 创建mime类型邮件
    final MimeMessage message = new MimeMessage(session);
    // 设置发信人
    message.setFrom(new InternetAddress(authenticator.getUsername()));
    // 设置收件人们
    final int num = recipients.size();
    InternetAddress[] addresses = new InternetAddress[num];
    for (int i = 0; i < num; i++) {
        addresses[i] = new InternetAddress(recipients.get(i));
    }
    message.setRecipients(RecipientType.TO, addresses);
    // 设置主题
    message.setSubject(subject);
    // 设置邮件内容
    message.setContent(content.toString(), "text/html;charset=utf-8");
    // 发送
    Transport.send(message);
    }
  
    /**
     * 发送邮件
     * 
     * @param recipient
     *                收件人邮箱地址
     * @param mail
     *                邮件对象
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(String recipient, SimpleMail mail)
        throws AddressException, MessagingException {
    send(recipient, mail.getSubject(), mail.getContent());
    }
  
    /**
     * 群发邮件
     * 
     * @param recipients
     *                收件人们
     * @param mail
     *                邮件对象
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(List recipients, SimpleMail mail)
        throws AddressException, MessagingException {
    send(recipients, mail.getSubject(), mail.getContent());
    }
  
}

调用上面的邮箱发送器,可以构建一个工厂类,工厂类可以封装创建的过程,所以通过读配置文件获取邮箱用户名,密码都会变得十分方便。下面的代码是我在写观察者模式的时候写的,只是简单演示了工厂类。
import com.mzule.dp.observer.constant.MailSenderType;
import com.mzule.simplemail.SimpleMailSender;
  
/**
 * 发件箱工厂
 * 
 */
public class MailSenderFactory {
  
    /**
     * 服务邮箱
     */
    private static SimpleMailSender serviceSms = null;
  
    /**
     * 获取邮箱
     * 
     * @param type 邮箱类型
     * @return 符合类型的邮箱
     */
    public static SimpleMailSender getSender(MailSenderType type) {
    if (type == MailSenderType.SERVICE) {
        if (serviceSms == null) {
        serviceSms = new SimpleMailSender("[email protected]",
            "hidden");
        }
        return serviceSms;
    }
    return null;
    }
  
}

发送邮件,还是观察者模式DEMO里面的代码
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
  
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
  
import com.mzule.dp.observer.constant.MailSenderType;
import com.mzule.dp.observer.factory.MailSenderFactory;
import com.mzule.dp.observer.po.Product;
import com.mzule.simplemail.SimpleMailSender;
  
public class ProductPriceObserver implements Observer {
  
    @Override
    public void update(Observable obj, Object arg) {
		Product product = null;
		if (obj instanceof Product) {
			product = (Product) obj;
		}
		if (arg instanceof Float) {
			Float price = (Float) arg;
			Float decrease = product.getPrice() - price;
			if (decrease > 0) {
				// 发送邮件
				SimpleMailSender sms = MailSenderFactory
					.getSender(MailSenderType.SERVICE);
				List recipients = new ArrayList();
				recipients.add("[email protected]");
				recipients.add("[email protected]");
				try {
					for (String recipient : recipients) {
					sms.send(recipient, "价格变动", "您关注的物品"
						+ product.getName() + "降价了,由"
						+ product.getPrice() + "元降到" + price + "元,降幅达"
						+ decrease + "元人民币。赶快购物吧。");
					}
				} catch (AddressException e) {
					e.printStackTrace();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
    }
}

OK

下面是离线邮箱服务器发送代码

离线邮箱服务器设置,麻烦自行百度一下,下载一个邮箱服务器,注册本地邮箱账户即可。。

附上代码:
package cn.itcast.shop.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送工具类
 *
 */
public class MailUitls {
	/**
	 * 发送邮件的方法
	 * @param to	:收件人
	 * @param code	:激活码
	 */
	public static void sendMail(String to,String code){
		/**
		 * 1.获得一个Session对象.
		 * 2.创建一个代表邮件的对象Message.
		 * 3.发送邮件Transport
		 */
		// 1.获得连接对象
		Properties props = new Properties();
		props.setProperty("mail.host", "localhost");
		Session session = Session.getInstance(props, new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("[email protected]", "111");
			}
			
		});
		// 2.创建邮件对象:
		Message message = new MimeMessage(session);
		// 设置发件人:
		try {
			message.setFrom(new InternetAddress("[email protected]"));
			// 设置收件人:
			message.addRecipient(RecipientType.TO, new InternetAddress(to));
			// 抄送 CC   密送BCC
			// 设置标题
			message.setSubject("你好");
			// 设置邮件正文:
			message.setContent("来自我衷心的问候!");
			// 3.发送邮件:
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		sendMail("[email protected]","11111111111111");
	}
}

java发送邮件的简单demo基本就这些。。

谢谢大家。。

下面是邮件发送的demo下载。。
demo下载,导入。即可使用..
http://download.csdn.net/detail/love_xiolan/9758930













你可能感兴趣的:(java,email,spring,邮箱,邮件,java,spring,email)