JavaMail学习之基础篇

因为项目要做邮件提醒方面的功能,就自学了一下JavaMail。将一些基础的知识记录下来:

demo1.java

package com.cz.email;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
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 Demo1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties props = new Properties();
		//设置服务器验证
		props.setProperty("mail.smtp.auth", "true");
		//设置传输协议
		props.setProperty("mail.transport.protocol", "smtp");
		Session session = Session.getInstance(props);
		//显示邮件发送过程中的交互信息
		session.setDebug(true);
		
		Transport transport = null;
		try {
			Message msg = new MimeMessage(session);
			//邮件内容
			msg.setText("我的学习云");
			//邮件发送方
			msg.setFrom(new InternetAddress("[email protected]"));

			transport = session.getTransport();
			//设置服务器类型,端口号,用户名,密码
			transport.connect("smtp.sina.com", 25, "mylearn", "123456");
			//邮件接收方
			transport.sendMessage(msg,
					new Address[]{new InternetAddress("[email protected]")});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				transport.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

 

demo2.java:

package com.cz.email;

import java.util.Properties;

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

public class Demo2 {
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		
		Properties props = new Properties();
		//设置服务器验证
		props.setProperty("mail.smtp.auth", "true");
		//设置传输协议
		props.setProperty("mail.transport.protocol", "smtp");
		//选择服务类型
		props.setProperty("mail.host", "smtp.sina.com");
		//通过认证创建一个session实例
		Session session = Session.getInstance(props,
				new Authenticator()
				{
					protected PasswordAuthentication getPasswordAuthentication()
					{
						return new PasswordAuthentication("mylearn","123456");
					}
				}
		);
		//显示邮件发送过程中的交互信息
		session.setDebug(true);
		
		Message msg = new MimeMessage(session);
		//邮件发送人
		msg.setFrom(new InternetAddress("[email protected]"));
		//邮件主题
		msg.setSubject("你好啊");
		//邮件接收方
		msg.setRecipients(RecipientType.TO, 
				InternetAddress.parse("[email protected],[email protected]"));
		//邮件内容
		msg.setContent("<span style='color:blue'>中文呵呵呵</span>", "text/html;charset=gbk");		
		Transport.send(msg);
		
	}


}

 上传一下开发的jar包:mail.jar

你可能感兴趣的:(javamail)