---
title: "发送邮件"
author: "fyd222"
date: "2012-04-02T13:38:30Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-04-02T13:38:30Z"
id: 1473067
url: "https://fyd222.iteye.com/blog/1473067"
---

[在java应用程序中加入发送邮件的功能](http://www.blogjava.net/jjshcc/archive/2010/07/21/326771.html)

javaMai 为建立邮件和消息服务提供了框架,因而应用程序可以发送和接收邮件.JavaMail API 是一个用于阅读、编写和发送电子消息的可选包（标准扩展），可以用来建立基于标准的电子邮件客户机，它配置了各种因特网邮件协，包括SMTP 、POP 、IMAP和 MIME ，还包括相关的NNTP 、S/MIME 及其它协议。   
   通常开发JavaMail 程序通常需要mail.jar 和 activation.jar 两个架包。mail.jar包含mailapi.jar、pop3.jar 和 smtp.jar。mailapi.jar包含核心的API 类, pop3.jar 和 smtp.jar为各自的邮件协议包含实现方法. activation.jar处理 MIME (多用途因特网邮件扩展)类型。 

   核心JavaMail API 由七个类组成：Session 、Message 、Address 、Authenticator 、Transport 、Store 及 Folder ，它们都来自javax.mail 、即JavaMail API 顶级包。可以用这些类完成大量常见的电子邮件任务，包括发送消息、检索消息、删除消息、认证、回复消息、转发消息、管理附件、处理基于HTML文件格式的 消息以及搜索或过滤邮件列表。   
这里只具体说明一下发送邮件的JavaMail类：   
1.Session   
这个Session类代表JavaMail 中的一个邮件session. 每一个基于 JavaMail的应用程序至少有一个session但是可以有任意多的session。   
     在这个例子中, Session对象需要知道用来处理邮件的SMTP 服务器。JavaMail需要Properties来创建一个session对象   
Session sendMailSession;   
    Properties props = new Properties ();   
props.put("mail.smtp.host", "smtp.sina.com.cn");//可以换上你的smtp主机名。   
sendMailSession = Session.getInstance(props, null);   
2.Transport   
Transport 是用来发送信息的.   
用法：Transport transport;   
transport = sendMailSession.getTransport("smtp");   
用JavaMail Session对象的getTransport 方法来初始化Transport。传过去的字符串申明了对象所要使用的协议，如"smtp"。这是因为JavaMail以境内置了很多协议的实现方法。  
注意: JavaMail并不是绝对支持每一个协议，目前支持IMAP、 SMTP和 POP3。   
3.Message   
Message对象将存储我们实际发送的电子邮件信息，Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。   
使用方法：Message newMessage = new MimeMessage(sendMailSession);   
4.MimeMessage   
    实现Message接口，以显示Mime风格的消息   
5.InternetAddress   
    存储电子邮件中关于“from”、“to”域的信息 

用JavaMail发送电子邮件的过程比较简单，大致分为以下5个步骤：   
1.创建Properties 对象，设置邮件服务器属性：mail.smtp.host ，即指定你的SMTP服务器。   
2.建立一个邮件会话   
3.创建你的邮件信息对象，该对象包含了你的邮件的全部内容，包括发送人，接受人，标题，正文，附件等内容   
4.完成发送前的服务器验证   
5.发送邮件

import java.io.\*;                                                                                                                 
import java.text.\*;                                                                                                               
import java.util.\*;                                                                                                               
import javax.activation.DataHandler;                                                                                                
import javax.activation.FileDataSource;                                                                                           
import javax.mail.\*;                                                                                                              
import javax.mail.internet.\*;                                                                                                     
                                                                                                                                  
public class SimpleSender {                                                                                                       
                                                                                                                                  
 public static void main(String args\[]) {                                                                                         
  try {                                                                                                                           
   String smtpServer = "smtp.sina.com.cn";                                                                                        
   String to = "test1@sina.com.cn";                                                                                               
   String from = "test2@sina.com.cn";                                                                                             
   String subject = "hello";                                                                                                      
   String body = "";                                                                                                              
   send(smtpServer, to, from, subject, body);                                                                                     
  } catch (Exception ex) {                                                                                                        
   System.out.println("Usage: java test.SimpleSender"                                                                             
     + " smtpServer toAddress fromAddress subjectText bodyText");                                                                 
  }                                                                                                                               
                                                                                                                                  
 }                                                                                                                                
                                                                                                                                  
 public static void send(String smtpServer, String to, String from,                                                               
   String subject, String body) {                                                                                                 
  try {                                                                                                                           
    Properties props = System.getProperties();                                                                                    
    props.put("mail.smtp.host", smtpServer);                                                                                      
    props.put("mail.smtp.auth","true");                                                                                           
    Authenticator  sa = new SmtpAuth(from, "");                                                                                   
           Session session = Session.getDefaultInstance(props,sa);                                                                
           InternetAddress     fromadress   =   new   InternetAddress(from);                                                      
           javax.mail.internet.InternetAddress   toadress=   new   javax.mail.internet.InternetAddress   (to);                    
           javax.mail.internet.MimeMessage     mymessage   =   new   javax.mail.internet.MimeMessage   (session);                 
           mymessage.setFrom(fromadress);                                                                                         
           mymessage.setRecipient(Message.RecipientType.TO   ,toadress);                                                          
           mymessage.setSentDate(new   java.util.Date());                                                                         
           mymessage.addHeader("header","test")   ;                                                                               
           mymessage.setSubject(subject)   ;                                                                                      
           mymessage.setText("hello")   ;                                                                                         
           Transport   tt=session.getTransport("smtp");                                                                           
           tt.send(mymessage);                                                                                                    
  } catch (Exception ex) {                                                                                                        
   System.out.println(ex.toString());                                                                                             
  }                                                                                                                               
                                                                                                                                  
 }                                                                                                                                
}