JavaMail创建和发送邮件

JavaMail API提供一些邮件系统模型类。


JavaMail API Packages
Package Description
javax.mail
The JavaMail TM API provides classes that model a mail system.
javax.mail.event
Listeners and events for the JavaMail API.
javax.mail.internet
Classes specific to Internet mail systems.
javax.mail.search
Message search terms for the JavaMail API.
javax.mail.util
JavaMail API utility classes.

  • javax.mail包定义邮件系统的常用类。
  • javax.mail.interner包定义基于Internet标准的特定的邮件系统类。例如MIME,SMTP,POP3和IMAP
javaMail API包括javax.mail包和子包。

下面的代码可以发送一个纯文本消息
    Properties props = new Properties();
    props.put("mail.smtp.host", "my-mail-server");
    Session session = Session.getInstance(props, null);

    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom("me@example.com");
        msg.setRecipients(Message.RecipientType.TO,
                          "you@example.com");
        msg.setSubject("JavaMail hello world example");
        msg.setSentDate(new Date());
        msg.setText("Hello, world!\n");
        Transport.send(msg, "me@example.com", "my-password");
    } catch (MessagingException mex) {
        System.out.println("send failed, exception: " + mex);
    }

Properties(属性)

JavaMail API 支持一下属性,可以设置在Session对象或Properties对象用于创建Session对象。属性通常设置为字符串类型;下表展示属性及其描述。
通常使用
props.put("mail.debug", "true");
为mail.debug设置属性值。

NameTypeDescription
mail.debugbooleanThe initial debug mode. Default is false.
mail.fromStringThe return email address of the current user, used by the InternetAddress methodgetLocalAddress.
mail.mime.address.strictbooleanThe MimeMessage class uses the InternetAddress method parseHeader to parse headers in messages.
This property controls the strict flag passed to the parseHeader method. The default is true.
mail.hostStringThe default host name of the mail server for both Stores and Transports. Used if themail.protocol.host property isn't set.
mail.store.protocolStringSpecifies the default message access protocol. The Session method getStore() returns a Store object that implements this protocol.
 By default the first Store provider in the configuration files is returned.
mail.transport.protocolStringSpecifies the default message transport protocol. The Session method getTransport()returns a Transport object
that implements this protocol.
By default the first Transport provider in the configuration files is returned.
mail.userStringThe default user name to use when connecting to the mail server. Used if themail.protocol.user property isn't set.
mail.protocol.classStringSpecifies the fully qualified class name of the provider for the specified protocol. Used in cases
where more than one provider for a given protocol exists; this property can be used to specify which provider to use by default. The provider must still be listed in a configuration file.
mail.protocol.hostStringThe host name of the mail server for the specified protocol. Overrides the mail.hostproperty.
mail.protocol.portintThe port number of the mail server for the specified protocol. If not specified the protocol's default port number is used.
mail.protocol.userStringThe user name to use when connecting to mail servers using the specified protocol. Overrides the mail.user property.



下面代码为发送一个普通邮件和发送一个含附件的邮件。
package javaMail;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {

	public static void main(String args[]){
		String to = "XXX@com.cn";//收件人
		String from = "XXXX@sari.ac.cn";//发件人
		String password = "password";//发件人邮箱密码
		String host = "smtp.XXX.cn";//服务器主机
		boolean debug = true;//是否需要debug
		
		String filename = "D:\\books\\javamail.txt";
		
		//配置发送邮件的环境属性
		Properties props = new Properties();
		props.put("mail.smtp.host", host);
		props.put("mail.debug", debug);
		
		//创建包含邮件服务器的网络连接信息的Session对象
		//Session类定义整个应用程序所需的环境信息。
		//Session对象根据这些邮件信息构建 用于邮件收发的Transport和Store对象,以及客户端创建Message对象时提供信息支持
		Session session = Session.getInstance(props);
		
		try {
			//创建代表邮件内容的Message对象
			//message对象:创建和解析邮件的核心API,它的实例对象代表一封电子邮件
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = {new InternetAddress(to)};
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject("java mail 测试");
			msg.setSentDate(new Date());
			
			//创建Transport对象,链接服务器
			//Transport是发送邮件的核心API类,它的实例对象代表了 实现某个邮件发送协议的邮件发送对象,例如SMTP协议
			Transport ts = session.getTransport(); 
			ts.connect("smtp.cstnet.cn", "OA_Feedback@sari.ac.cn", "sari112233");
			
			//发送Message
			//发送简单邮件
			setTextContent(msg);
			msg.saveChanges();
			ts.sendMessage(msg, msg.getAllRecipients());
			
			//发送添加附件的邮件
			setFileAsAttachment(msg,filename);
			msg.saveChanges();
			ts.sendMessage(msg, address);
			//关闭连接
			ts.close();
		} catch (MessagingException mex) {
			 // Prints all nested (chained) exceptions as well
            mex.printStackTrace();
            // How to access nested exceptions
            while (mex.getNextException() != null) {
                // Get next exception in chain
                Exception ex = mex.getNextException();
                ex.printStackTrace();
                if (!(ex instanceof MessagingException)) break;
                else mex = (MessagingException)ex;
            }
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//发送简单的,只包含文本的邮件
	public static void setTextContent(Message msg) throws MessagingException{
		String content = "发送简单的,只包含文本的邮件";
		msg.setContent(content, "text/html;charset=UTF-8");
	}
	
	//发送添加附件的邮件
	public static void setFileAsAttachment(Message msg,String filename) throws MessagingException, IOException{
		//MimeBodyPart表示邮件的一个MIME信息
		MimeBodyPart mbp1 = new MimeBodyPart();
		mbp1.setText("测试发送添加附件的邮件");
		
		MimeBodyPart mbp2 = new MimeBodyPart();
		mbp2.attachFile(filename);
		
		//Multipart类表示一个由多个MIME消息组合成的组合MIME消息
		//创建Multipart,将BodyParts添加到Multipart
		Multipart mp = new MimeMultipart();
		mp.addBodyPart(mbp1);
		mp.addBodyPart(mbp2);
		//将Multipart作为消息的内容
		msg.setContent(mp);
	}
}

源码来自:https://github.com/yangnn/javaMail


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值