利用JAVA API发送E-mail

 /**
 *
 * 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.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.put("mail.smtp.host", host);
                        else
                                throw new Exception("没有指定发送邮件服务器");
                        if (needAuth)
                                props.put("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(javax.mail.Message.RecipientType.TO,
                                                InternetAddress.parse(to));
                        else
                                throw new Exception("没有指定收件人地址");
                        //指定抄送给谁
                        if (cc != null)
                                msg.addRecipients(javax.mail.Message.RecipientType.CC,
                                                InternetAddress.parse(cc));
                        //制定隐藏抄送给谁
                        if (bc != null)
                                msg.addRecipients(javax.mail.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();
                        //发送邮件服务器(SMTP),简单邮件传输协议
                        Transport transport = s.getTransport("smtp");
                        //访问邮件服务器
                        transport.connect(host, user, pass);
                        //发送信息
                        transport.sendMessage(msg, msg.getAllRecipients());
                        //关闭邮件传输
                        transport.close();
                } catch (Exception e) {
                        throw new Exception("发送邮件失败:", e);
                }
        }
}

 

sendmail.jsp:

  <%@ page contentType="text/html;charset=gb2312" language="java" %>
<%@ page import="ten.*,simpleforum.util.*"%>
<!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 = ParamUtil.getParameter(request,"host");
 String user = ParamUtil.getParameter(request,"user");
 String password = ParamUtil.getParameter(request,"password");
 String subject = ParamUtil.getParameter(request,"subject");
 String to = ParamUtil.getParameter(request,"to");
 String from = ParamUtil.getParameter(request,"from");
 String bodyashtml = ParamUtil.getParameter(request,"bodyashtml");
 String attachfile = ParamUtil.getParameter(request,"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);
   send.setUser(user);
   send.setPass(password);
   send.setSubject(subject);
   send.setTo(to);
   send.setFrom(from);
   send.setBodyAsHTML(bodyashtml);
   send.addAttachFromFile(attachfile,"aa.txt");
   send.send();
   out.println("<br>邮件发送成功!!!");
  } catch (Exception e) {
   out.println("<br>"+e.getMessage());
   out.println("<br>邮件发送失败!!!");
  }
%>
</body>
</html>

testmail.jsp:

<%@ page contentType="text/html;charset=gb2312" language="java" %>
<%@ page import="ten.*"%>
<!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>
<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="mail.keylab.net"></td>
   </tr>
   <tr>
    <td>用户名</td><td><input type="text" name="user" value="wangmj@keylab.net"></td>
   </tr>
   <tr>
    <td>密码</td><td><input type="password" name="password" value="root3wmj"></td>
   </tr>
   <tr>
    <td>邮件主体</td><td><input type="text" name="subject" value="邮件发送测试"></td>
   </tr>
   <tr>
    <td>收件人</td><td><input type="text" name="to" value="wangmj@keylab.net"></td>
   </tr>
   <tr>
    <td>发送人</td><td><input type="text" name="from" value="wangmj@keylab.net"></td>
   </tr>
   <tr>
    <td>邮件内容</td><td><input type="text" name="bodyashtml" value="大家好!邮件测试。"></td>
   </tr>
   <tr>
    <td>附件</td><td><input type="text" name="attachfile" value="d://myforum.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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值