HTMl:
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<title>撰写邮件</title> 
</head> 
<body> 
<form action="testall.jsp" method="post" name="form1"> 
<table width="424" border="0" align="center" cellspacing="1" bgcolor="#006600" class="black" height="287"> <tr bgcolor="#FFFFFF"> 
<td width="102" height="29"><font face="宋体"><font size="3">收信人</font>:</font></td> 
<td width="308" height="23"> <input name="to1" type="text" id="to1" size="19"><font size="2"><i><font face="Basemic Times">@&nbsp; 
  </font></i></font><input name="to2" type="text" id="to2" size="17"></td> 
</tr> <tr bgcolor="#FFFFFF"> 
<td width="102" height="12"><font size="3"><font face="宋体">寄信人</font></font><font face="宋体">:</font></td> 
<td width="308" height="23"> <input name="from1" type="text" id="from1" size="19"><i><font face="Basemic Times" size="2">@&nbsp; 
  </font></i><input name="from2" type="text" id="from2" size="17"></td>  
</tr> <tr bgcolor="#FFFFFF"> 
<td width="102" height="14"><font size="3"><font face="宋体">用户名</font></font><font face="宋体">:</font></td> 
<td width="308" height="25"> <input name="yhm" type="text" id="yhm" size="41">  
</tr>  <tr bgcolor="#FFFFFF">
<td width="102" height="14"><font size="3"><font face="宋体">密&nbsp; 码</font></font><font face="宋体">:</font></td> 
<td width="308" height="25"> <input name="mm" type="text" id="mm" size="41"> 
</tr><tr bgcolor="#FFFFFF"> 
<td width="102" height="25"><font size="3" face="宋体">主&nbsp; 题:</font></td> 
<td width="308" height="25"> <input name="title" type="text" id="title" size="41"></td> 
</tr> 
<tr> 
<td height="25" colspan="2" bgcolor="#FFFFFF" width="401"><font size="3"><font face="宋体">信件类型</font>:&nbsp; 
  </font><select name="emailtype" id="emailtype" size="1">         
<option value="text/plain">Text</option> 
<option value="text/html">Html</option> 
<option selected>-Select-</option>
</select></td> 
</tr> 
<tr> 
<td height="63" colspan="2" bgcolor="#FFFFFF" width="401"><textarea name="content" cols="56" rows="8" id="content"></textarea></td> 
</tr> <tr align="center" valign="bottom"> 
<td colspan="2" bgcolor="#FFFFFF" width="401" height="33">
  <p align="left"><font size="3">附件(本地):</font>    
   <input name="fj2" type="file" id="fj2" size="47"></p>    
</td> 
</tr> 
<tr align="center"> 
<td colspan="2" bgcolor="#FFFFFF" width="401" height="11"> <input type="submit" name="Submit" value="发送"> 
<input type="reset" name="Submit2" value="重置"></td> 
</tr> 
</table> 
</form> 
</body> 
</html> 
JSP(testall.jsp):
<%@ page contentType="text/html;charset=GB2312" %> 
<%request.setCharacterEncoding("gb2312");%> 
<%@ page import="java.util.*,javax.mail.*"%> 
<%@ page import="javax.mail.internet.*"%> 
<%@ page import="javax.activation.*"%><!--要发送附件必须引入该库--> <html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<title>发送成功</title> 
</head> 
<body> 
<% 
try{ 
String tto1=request.getParameter("to1"); 
String tto2=request.getParameter("to2"); 
String tfrom1=request.getParameter("from1"); 
String tfrom2=request.getParameter("from2"); 
String tyhm=request.getParameter("yhm"); 
String tmm=request.getParameter("mm"); 
String ttitle=request.getParameter("title"); 
String emailtype=request.getParameter("emailtype");//获取email类型 
String tcontent=request.getParameter("content"); 
//String tfj1=request.getParameter("fj1"); 
String tfj2=request.getParameter("fj2"); 
String tfj3=request.getParameter("fj3"); String smtptype="";
if(tfrom2.equals("163.com"))
{smtptype="smtp.163.com";
  }//支持
  else if(tfrom2.equals("126.com"))
{smtptype="smtp.126.com";
  }//支持
  else if(tfrom2.equals("21cn.com"))
{smtptype="smtp.21cn.com";
  }//支持
  else if(tfrom2.equals("yahoo.com.cn"))
{smtptype="smtp.mail.yahoo.com.cn";
  }//支持
else if(tfrom2.equals("tom.com"))
{smtptype="smtp.tom.com";
  }//支持
  else if(tfrom2.equals("263.net"))
{smtptype="smtp.263.net";
  }//未试
  else if(tfrom2.equals("mail.china.com"))
{smtptype="mail.china.com";
  }//不支持
  else if(tfrom2.equals("sina.com"))
{smtptype="smtp.sina.com";
  }//不支持
  Properties props=new Properties(); 
props.put("mail.smtp.host",smtptype); 
props.put("mail.smtp.auth","true"); 
Session s=Session.getInstance(props); 
s.setDebug(true); MimeMessage message=new MimeMessage(s); //给消息对象设置发件人/收件人/主题/发信时间 
InternetAddress from=new InternetAddress(tfrom1+"@"+tfrom2,tfrom1); 
message.setFrom(from); 
InternetAddress to=new InternetAddress(tto1+"@"+tto2); 
message.setRecipient(Message.RecipientType.TO,to); 
message.setSubject(ttitle); 
message.setSentDate(new Date()); Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放多个BodyPart对象 //设置信件文本内容 
BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象 
mdp.setContent(tcontent,emailtype+";charset=gb2312");//给BodyPart对象设置内容和格式/编码方式 
mm.addBodyPart(mdp);//将含有信件内容的BodyPart加入到MimeMultipart对象中 //设置信件的附件1(自定义附件:直接将所设文本内容加到自定义文件中作为附件发送) 
//mdp=new MimeBodyPart();//新建一个存放附件的BodyPart 
DataHandler dh=new DataHandler(tfj2,"text/plain;charset=gb2312"); 
//新建一个DataHandler对象,并设置其内容和格式/编码方式 
//mdp.setFileName("text.txt");//加上这句将作为附件发送,否则将作为信件的文本内容 
//mdp.setDataHandler(dh);//给BodyPart对象设置内容为dh 
//mm.addBodyPart(mdp);//将含有附件的BodyPart加入到MimeMultipart对象中 //设置信件的附件2(用本地上的文件作为附件) 
mdp=new MimeBodyPart(); 
FileDataSource fds=new FileDataSource(tfj2); 
dh=new DataHandler(fds); 
int ddd=tfj2.lastIndexOf("\\"); 
String fname=tfj2.substring(ddd);//提取文件名 
String ffname=new String(fname.getBytes("gb2312"),"ISO8859-1");//处理文件名是中文的情况 
mdp.setFileName(ffname);//可以和原文件名不一致,但最好一样 
mdp.setDataHandler(dh); 
mm.addBodyPart(mdp); 
//设置信件的附件3(用远程文件作为附件) 
//mdp=new MimeBodyPart(); 
/*URL urlfj=new URL(tfj3); 
URLDataSource ur=new URLDataSource(urlfj); 
//注:这里用的参数只能为URL对象,不能为URL字串,在前面类介绍时有误(请谅解),这里纠正一下. 
dh=new DataHandler(ur); 
int ttt=tfj3.lastIndexOf("/"); 
String urlname=tfj3.substring(ttt); 
//String urlfname=new String(urlname.getBytes("gb2312"),"ISO8859-1");//不知怎么回事,这里不能处理中文问题 
mdp.setFileName(urlname); 
mdp.setDataHandler(dh); 
mm.addBodyPart(mdp); 
*/
message.setContent(mm);//把mm作为消息对象的内容 message.saveChanges(); 
Transport transport=s.getTransport("smtp"); 
transport.connect(smtptype,tyhm,tmm); 
transport.sendMessage(message,message.getAllRecipients()); 
transport.close(); %> 
<div align="center"> 
<p><font color="#FF6600">发送成功!</font></p> <br> 
<a href="m.html">再发一封</a> </p> 
</div> 
<% 
}catch(MessagingException e){ 
out.println(e.toString()); 
} %> 
</body> 
</html> 

解决方案 »

  1.   

    import java.net.URL;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;import javax.activation.*;
    /**
     * 邮件发送类,用于发送邮件及附件
     * 支持mime格式及Html,支持多附件
     * <p>Title: 冰云工作室</p>
     * <p>Description: 邮件发送</p>
     * <p>Copyright: Copyright (c) 2003</p>
     * <p>Company: [email protected]</p>
     * @author 冰云
     * @version 1.0 August.23rd 2003
     * @todo 使用者请修改Logger.log为System.out.println
     */
    public class SendMail {  private MimeMessage mimeMsg; //MIME邮件对象
      private Session session; //邮件会话对象
      private Properties props; //系统属性
      private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象  private String authentication = "false"; //smtp是否需要认证
      private String username = ""; //smtp认证用户名和密码
      private String password = "";
      private String from = "";
      private String to = "";
      private String cc = "";
      private String bcc = "";
      private String body = "";
      private String subject = "";
      private String host = "";
      private String reply = "";
      private String sender = "";
      private String date = "";
      private boolean textmail = true;  private String mailtype = PLAIN;  private static final String HTML = "text/html;charset=GB2312";
      private static final String PLAIN = "text/plain; charset=GB2312";  private ArrayList attachment = new ArrayList();
      /**
       *
       */
      public SendMail() {
        this(true);
      }  public SendMail(boolean textmail) {
        this.textmail = textmail;
        this.mailtype = textmail ? PLAIN : HTML;  }  public SendMail(String from, String to, String subject, String body) {
        this();
        loadDefault();
      }
      private boolean createMimeMessage() {
        try {
          //     Logger.log(this,"createMimeMessage():准备获取邮件会话对象!");
          session = Session.getDefaultInstance(props, null); //获得邮件会话对象
        }
        catch (Exception e) {
          //Logger.logerr(this, "createMimeMessage():获取邮件会话对象时发生错误!");
         // Logger.logerr(this, e);
         System.out.println(e+"1");
          return false;
        }    try {
          mimeMsg = new MimeMessage(session); //创建MIME邮件对象
          mp = new MimeMultipart();
          return true;
        }
        catch (Exception e) {
         System.out.println(e+"2");
          //Logger.logerr(this, "createMimeMessage():创建MIME邮件对象失败!");
         // Logger.logerr(this, e);
          return false;
        }
      }  private boolean initMail() {
        if (props == null) {
          props = System.getProperties(); //获得系统属性对象
        }
        if ("".equals(host)) { // 设置主机
          loadDefault();
        }
        props.put("mail.smtp.host", host); //设置SMTP主机
          if (!this.createMimeMessage())
            return false;
        props.put("mail.smtp.auth", authentication); //设置认证
        try {
          if (!"".equals(subject)) // 设置标题
            mimeMsg.setSubject(subject);
          if (!"".equals(from)) //设置发信人
            mimeMsg.setFrom(new InternetAddress(from));
          if (!"".equals(to)) // 设置收信人
            mimeMsg.setRecipients(Message.RecipientType.TO,
                                  InternetAddress.parse(to));
          if (!"".equals(cc)) //  设置抄送
            mimeMsg.setRecipients(Message.RecipientType.CC,
                                  (Address[]) InternetAddress.parse(cc));
          if (!"".equals(bcc)) // 设置密件抄送
            mimeMsg.setRecipients(Message.RecipientType.BCC,
                                  (Address[]) InternetAddress.parse(bcc));      if (!"".equals(reply)) //设置回复
            mimeMsg.setReplyTo( (Address[]) InternetAddress.parse(reply));
            //    if (!"".equals(date)) //设置日期
            //     mimeMsg.setSentDate(new Date(date));      if (!"".equals(body)) { // 设置内容
            if (!this.textmail) {
              BodyPart bp = new MimeBodyPart();
              bp.setContent(body, mailtype);
              mp.addBodyPart(bp);
            }
            else {
              mimeMsg.setText(body);
            }
          }
          if (!attachment.isEmpty()) { // 设置附件
            for (Iterator it = attachment.iterator(); it.hasNext(); ) {
              BodyPart bpr = new MimeBodyPart();
              MimeBodyPart mdp = new MimeBodyPart() ;
              //URL urlfj = new URL((String) it.next()) ;
              //URLDataSource fileds = new URLDataSource(urlfj) ;
              FileDataSource fileds = new FileDataSource( (String) it.next());
              bpr.setDataHandler(new DataHandler(fileds));
              bpr.setFileName(fileds.getName());
              mp.addBodyPart(bpr);
            }
          }      return true;
        }
        catch (Exception e) {
          //Logger.logerr(this, "initMail():设置邮件发生错误!");
          //Logger.logerr(this, e);
         System.out.println(e+"3");
          return false;
        }
      }  public boolean Send() {
        try {
          if (initMail()) {
            if (mp.getCount() > 0)
              mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            //Logger.log(this, "正在发送邮件....");        Session mailSession = Session.getInstance(props, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect( (String) props.get("mail.smtp.host"), username,
                              password);
            transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());        //Logger.log(this, "发送邮件成功!");
            transport.close();        return true;
          }
          else {
            return false;
          }
        }
        catch (Exception e) {
         // Logger.logerr(this, "邮件发送失败!");
          //Logger.logerr(this, e);
         System.out.println(e+"4");
          return false;
        }  }  private void loadDefault() {
      }
      public void loadParameter()
      {
       this.host="210.51.191.87";
       this.username="dg";
       this.password="masdfgter";
       this.authentication = String.valueOf(false);
      }  public void setCc(String cc) {
        this.cc = cc;
      }  public void setBcc(String bcc) {
        this.bcc = bcc;
      }  public void setHost(String host, boolean auth) {
        this.host = host;
        this.authentication = String.valueOf(auth);
      }  public void setHost(String host, boolean auth, String username,
                          String password) {
        setHost(host, auth);
        setUsername(username);
        setPassword(password);  }  public void setHost(String host, String username, String password) {
        setHost(host, true);
        setUsername(username);
        setPassword(password);
      }  public void setHost(String host) {
        setHost(host, true);
      }  public void setFrom(String from) {
        this.from = from;
      }  public void setPassword(String password) {
        this.password = password;
      }  public void setTo(String to) {
        this.to = to;
      }  public void setUsername(String username) {
        this.username = username;
      }  public void setAttachment(String filename) {
        this.attachment.add(filename);
      }  public void setBody(String body) {
        this.body = body;
      }  public void setSubject(String subject) {
        this.subject = subject;
      }  public void setReply(String reply) {
        this.reply = reply;
      }  public void setSender(String sender) {
        this.sender = sender;
      }  public static void main(String[] argc) {
    SendMail send = new SendMail(false);
    send.setHost("mail.nettoo.com.cn","[email protected]","sdfsd");
    send.setFrom("[email protected]"); send.setBody("你好");
    send.setSubject("您好,");
    send.setAttachment("neteaselogo.gif");
    send.setTo("[email protected]");
          
          if (send.Send()) {
            System.out.print("Send successful.");
          }
          else {
            System.out.print("Send failed.");
          }
          }}