JAVA MAIL发送邮件

JAVA MAIL API
一、Java Mail API本质上是基于SMTP协议、POP协议、IMAP协议和MIME协议
1、SMTP协议
   简单邮件传输协议是用于传送电子邮件的机制。在Java Mail API环境中,基于JavaMail的应用程序将于与Internet服务提供商的SMTP服务器通信,SMTP服务器把消息转发给用做接收消息的SMTP服务

器。
2、POP协议
   邮局协议是Internet上大多数人用来接收邮件的机制。
3、IMAP协议
   Internet消息访问协议是用于接收消息的更加高级的协议。
4、MIME协议
   多用途的国际邮件扩充协议定义传输的内容。
二、Java Mail开发包
Java Mail API的核心类包括会话、消息、地址、身份验证、传输、存储和文件夹。
1、会话类(Session)
   Session类定义了一个基本的邮件会话。Session对象利用java.util.Properties对象获取邮件服务器、用户名和密码等信息,以及其他可在整个应用程序中共享的信息。
   创建默认会话
Properties props = new Properties();
        …//填充Properties对象
        Session session = Session.getDefaultInstance(props,null);
   创建独特会话
        Properties props = new Properties();
        …//填充Properties对象
        Session session = Session.getInstance(props,null);
   Null参数是一种Authenticator(认证)对象
2、消息类(MimeMessage)
   一个MimeMessage对象是一种MIME类型和报头的消息。
   可以通过将Session对象传递给MimeMessage构造器的方法来创建消息:
   MimeMessage message = new MimeMessage(session);
   一旦创建了消息,就可以设置消息的各个部分
设置内容的基本机制是setContent()方法,它带有表示内容和MIME类型的参数。
   message.setContent("hello","text/plain");
如果消息是纯文本
   message.setText("hello");
设置主题
   message.setSubject("subject");
3、地址类
   用Address类为信件标上地址。
   要创建只带有电子邮件地址的地址,可以把电子邮件地址传递给Address类的构造器:
Address address = new InternetAddress("");
   如果想要一个名字出现在电子邮件地址后,也可以将其传递给构造器:
Address address = new InternetAddress("");
   地址与消息连接:setFrom()和setReplyTo()
4、身份验证类
   在创建时,必须用会话记录Authentication类。其后,当需要进行身份验证时,通知Authentication,将会弹出一个窗口,或从一个配置文件中读取用户名和密码,并把他们作为一个

PasswordAuthentication对象返回给调用程序。
Properties props = new Properties();
…//填充Properties对象
Authentication auth = new MyAuthenticator();
        Session session = Session.getDefaultInstance(props,auth);
5、传输类
   默认版本
   Transport.send(message);
   从用于协议的会话中获取一个特定的实例,然后传递用户名和密码并发送消息,最后关闭连接
   message.saveChanges();
        Transport transport = session.getTransport("smtp");
   transport.contect(host,username,password);
transport.sendMessage(message,message.getAllRecipients());
transport.close();
6、存储类和文件夹类
   Store store = session.getStore("pop3");
   store.connect(host,username,password);
   Folder folder = store.getFolder("INBOX");
   folder.open(Folder.READ_ONLY);
   Message message[] = folder.getMessages();
   对于POP3协议,唯一可用的文件夹是INBOX。如果使用的是IMAP协议,则可以使用其他的文件夹。
   一旦读取消息,可以用getContent()方法获取其内容,或使用writeTo()方法将其内容写到一个流中。getContent()方法只获取消息内容,而writeTo()方法则还会输出报头。
   System.out.println(((MimeMessage)message).getContent());
   读取完邮件后,就可以关闭对文件夹和存储的连接
   folder.close(aBoolean);
   store.close();
三、实例
package com.email;
/**
* @author star
* SendMail.java
*/
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Message;
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;
import javax.mail.internet.MimeUtility;

//import javax.mail.internet.MailDateFormat;

public class SendMail {
        public static String TEXT = "text/plain;charset=gb2312";
        public static String HTML = "text/html;charset=gb2312";
        private String host; //邮件服务器
        private String user; //用户名
        private String pass;//用户密码
        private String from;//发信人
        private String to;//收信人
        private String cc;//Carbon Copy, 抄送邮件给某人
        private String bc;//bcc Blind Carbon Copy,隐蔽副本 隐蔽抄送给某人
        private String subject;//邮件主题
        private BodyPart body;//邮件内容
        private boolean needAuth; //是否需要认证
        private List attaches;//邮件附件
/**
* 构造方法
*
*/
        public SendMail() {
                needAuth = true;
                attaches = new ArrayList();
        }
        /**
         * 构造方法
         * @param host
         */
        public SendMail(String host) {
                needAuth = true;
                attaches = new ArrayList();
                this.host = host;
        }
        /**
         * 构造方法
         * @param host
         * @param user
         * @param pass
         */
        public SendMail(String host, String user, String pass) {
                needAuth = true;
                attaches = new ArrayList();
                this.host = host;
                this.user = user;
                this.pass = pass;
        }
//设置邮件服务器是否需要认证
        public void setNeedAuth(boolean needAuth) {
                this.needAuth = needAuth;
        }
        public void setFrom(String from) {
                this.from = from;
        }
        public void setTo(String to) {
                this.to = to;
        }
        public String getPass() {
                return pass;
        }
        public String getUser() {
                return user;
        }
        public void setPass(String string) {
                pass = string;
        }
        public void setUser(String string) {
                user = string;
        }

        public String getFrom() {
                return from;
        }
        public String getHost() {
                return host;
        }
        public boolean isNeedAuth() {
                return needAuth;
        }
        public String getSubject() {
                return subject;
        }
        public void setHost(String string) {
                host = string;
        }
        public void setBlindTo(String bc) {
                this.bc = bc;
        }
        public void setCopyTo(String cc) {
                this.cc = cc;
        }
        public void setSubject(String subject) {
                this.subject = subject;
        }
/**
* 设置邮件内容的形式
* @param string
* @param contentType
*/
        public void setBody(String string, String contentType) {
                try {
                        body = new MimeBodyPart();
                        DataHandler dh = new DataHandler(string, contentType);
                        body.setDataHandler(dh);
                } catch (Exception exception) {
                }
        }
/**
* 设置邮件的内容的格式为文本格式
* @param string
*/
        public void setBodyAsText(String string) {
                setBody(string, TEXT);
        }
/**
* 以HTMl的形式存放内容
* @param string
*/
        public void setBodyAsHTML(String string) {
                setBody(string, HTML);
        }
/**
* 从文件中自动导入邮件内容
* @param filename
*/
        public void setBodyFromFile(String filename) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(filename);
                        DataHandler dh = new DataHandler(fds);
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 从一个URL导入邮件的内容
* @param url
*/
        public void setBodyFromUrl(String url) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        URLDataSource ur = new URLDataSource(new URL(url));
                        DataHandler dh = new DataHandler(ur);
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 将String中的内容存放入文件showname,并将这个文件作为附件发送给收件人
* @param string 为邮件的内容
* @param showname 显示的文件的名字
*/
        public void addAttachFromString(String string, String showname) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        DataHandler dh = new DataHandler(string, TEXT);
                        mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null));
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* filename为邮件附件
*在收信人的地方以showname这个文件名来显示
* @param filename
* @param showname
*/
        public void addAttachFromFile(String filename, String showname) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(filename);
                        DataHandler dh = new DataHandler(fds);
                        mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null));
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 将互联网上的一个文件作为附件发送给收信人
* 并在收信人处显示文件的名字为showname
* @param url
* @param showname
*/
        public void addAttachFromUrl(String url, String showname) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        URLDataSource ur = new URLDataSource(new URL(url));
                        DataHandler dh = new DataHandler(ur);
                        mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null));
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 发送邮件,需要身份认证
* @throws Exception
*/
        public void send() throws Exception {
                try {
                   //*****会话类*****//
                        Properties props = new Properties();
                        if (host != null && !host.trim().equals(""))
                                props.setProperty("mail.smtp.host", host);//key   value
                        else
                                throw new Exception("没有指定发送邮件服务器");
                        if (needAuth)
                                props.setProperty("mail.smtp.auth", "true");
                        Session s = Session.getInstance(props, null);
                        //*****消息类*****//
                        MimeMessage msg = new MimeMessage(s);               
                        msg.setSubject(subject);//设置邮件主题
                        msg.setSentDate(new Date());//设置邮件发送时间
                        //*****地址类*****//
                        if (from != null)
                                msg.addFrom(InternetAddress.parse(from));//指定发件人
                        else
                                throw new Exception("没有指定发件人");                       
                        if (to != null)
                                msg.addRecipients(Message.RecipientType.TO,InternetAddress.parse(to));//指定收件人
                        else
                                throw new Exception("没有指定收件人地址");                       
                        if (cc != null)
                                msg.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));//指定抄送                       
                        if (bc != null)
                                msg.addRecipients(Message.RecipientType.BCC,InternetAddress.parse(bc));//指定密送
                        Multipart mm = new MimeMultipart();
                        if (body != null)
                                mm.addBodyPart(body);//设置邮件的附件
                        for (int i = 0; i < attaches.size(); i++) {
                                BodyPart part = (BodyPart) attaches.get(i);
                                mm.addBodyPart(part);
                        }                    
                        msg.setContent(mm);//设置邮件的内容
                        //*****传输类*****//
                        msg.saveChanges();//保存所有改变                    
                        Transport transport = s.getTransport("smtp");//发送邮件服务器(SMTP)               
                        transport.connect(host, user, pass);//访问邮件服务器           
                        transport.sendMessage(msg, msg.getAllRecipients());//发送信息
                        transport.close();//关闭邮件传输
                } catch (Exception e) {
                   e.printStackTrace();
                        throw new Exception("发送邮件失败:", e);
                }
        }
}

测试类
index.jsp
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>发送邮件测试</title>
    <meta name="copyright" content="邮件发送测试. All rights reserver." />
    <meta name="Keywords" content="jsp,servlet,mail" />
    <meta name="Description" content="发送邮件测试" />
    <meta http-equiv="content-type" content="text/html;charset=gb2312" />
</head>
<body>
<form method="post" action="Sendmail.jsp">
   <table border="1" cellpadding="0" cellspacing="3" align="center">
    <tr>
     <td>邮件服务器</td><td><input type="text" name="host" value="smtp.yourServer.com"></td>
    </tr>
    <tr>
     <td>用户名</td><td><input type="text" name="user" value=">
    </tr>
    <tr>
     <td>密码</td><td><input type="password" name="password" value="123456"></td>
    </tr>
    <tr>
     <td>邮件主体</td><td><input type="text" name="subject" value="邮件发送测试"></td>
    </tr>
    <tr>
     <td>收件人</td><td><input type="text" name="to" value=">
    </tr>
    <tr>
     <td>发送人</td><td><input type="text" name="from" value=">
    </tr>
    <tr>
     <td>邮件内容</td><td><input type="text" name="bodyashtml" value="大家好!邮件测试。"></td>
    </tr>
    <tr>
     <td>附件</td><td><input type="text" name="attachfile" value="D:\test.txt"></td>
    </tr>
    <tr>
     <td><input type="submit" name="submit" value="发送" ></td>
     <td><input type="reset" name="reset" value="重置" ></td>
    </tr>
   </table>
</form>
</body>
</html>

Sendmail.jsp
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<%@ page import="com.email.*,com.tool.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>发送邮件测试</title>
<meta name="copyright" content="邮件发送测试. All rights reserved.">
<meta name="Keywords" content="jsp,servlet,mail">
<meta name="Description" content="发送邮件测试">
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<%
String host = request.getParameter("host");
String user = request.getParameter("user");
String password = request.getParameter("password");
String subject = request.getParameter("subject");
subject = new ToChinese().getGB2312(subject);
String to = request.getParameter("to");
String from = request.getParameter("from");
String bodyashtml = request.getParameter("bodyashtml");
bodyashtml = new ToChinese().getGB2312(bodyashtml);
String attachfile = request.getParameter("attachfile");
attachfile = new ToChinese().getGB2312(attachfile);
out.println("<br>"+host);
out.println("<br>"+user);
//out.println("<br>"+password);
out.println("<br>"+subject);
out.println("<br>"+to);
out.println("<br>"+from);
out.println("<br>"+bodyashtml);//邮件内容
out.println("<br>"+attachfile);//邮件附件
try {
    SendMail send = new SendMail();
    send.setHost(host);
    //System.out.println(host);
    send.setUser(user);
    //System.out.println(user);
    send.setPass(password);
    //System.out.println(password);
    send.setSubject(subject);
    //System.out.println(subject);
    send.setTo(to);
    //System.out.println(to);
    send.setFrom(from);
    //System.out.println(from);
    send.setBodyAsHTML(bodyashtml);//以HTML形式存放内容
    //System.out.println(bodyashtml);
    send.addAttachFromFile(attachfile,"aa.txt");//附件路径,附件名称
    //System.out.println(attachfile);
    send.send();
    out.println("<br>邮件发送成功!!!");
   } catch (Exception e) {
    out.println("<br>"+e.getMessage());
    out.println("<br>邮件发送失败!!!");
   }
%>
</body>
</html>

工具类ToChinese.java
package com.tool;

public class ToChinese{
    public ToChinese() {}
    public String getGB2312(String s){
     if (s != null && !"".equals(s)) {
    try {
     s = new String(s.getBytes("8859_1"), "gb2312");
     return s;
    } catch (Exception ex) {
     System.out.print(ex.getMessage());
    }
   }
   return "";
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>