这是我程中使用的sendMail,运行正常.
-----------------------------------------------------------
package com.ds.pub;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.*;/**
 * 发送普通邮件,接受普通邮件 发送带有附件的邮件,接收带有附件的邮件 
 * 发送html形式的邮件,接受html形式的邮件 发送带有图片的邮件等做了一个总结。
 */
public class SendMail {
 private String host ="ms.dlp.com.tw"; //"smtp.163.com";邮件服务器 private String username = "OA_Messenger"; //进入邮箱要的用户名 private String password = "0000"; //进入邮箱用的密码 private String mail_head_name = ""; //邮件标题 private String mail_head_value = "";//邮件标题 private String mail_to = "[email protected]";//收件者邮箱地址 private String mail_from = "[email protected]";//发件者邮箱地址 private String mail_subject = "this is the subject of this test mail"; //邮件标题 private String mail_body = "this is the mail_body of this test mail"; //邮件体 private String personalName = "OA系统提示邮件"; //显示发件者名称
 
 private String modelCode = "no";//发送邮件的模块.
 
 private String flag = "no";//是否记录数据库,默认为不记录
 public SendMail() {
 Varlist var = new Varlist();
 this.host = var.getEmail_host();
 this.username=var.getEmail_userName();
 this.password=var.getEmail_password();
 this.mail_from=var.getEmail_form();
 }
  /**
  * 此段代码用来发送普通电子邮件
  */
 public synchronized void send(){
  try {
   Properties props = new Properties(); // 获取系统环境
   Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
   String mailEncoding = "UTF-8";
   String textMimeType = "text/plain;charset=" +mailEncoding; 
   
   props.put("mail.smtp.host", host);
   props.put("mail.smtp.auth", "true");
   //Session session = Session.getDefaultInstance(props, auth);
   Session session = Session.getInstance(props,auth);
   // 设置session,和邮件服务器进行通讯。
   MimeMessage message = new MimeMessage(session);
   message.setContent(mail_body==null ? "" : mail_body,textMimeType); // 设置邮件格式
   message.setSubject(mail_subject == null ? "" : mail_subject,mailEncoding); // 设置邮件主题
   message.setText(mail_body,mailEncoding); // 设置邮件正文
   //message.setHeader(mail_head_name,mail_head_value); // 设置邮件标题
   message.setSentDate(new Date()); // 设置邮件发送日期
   Address address = new InternetAddress(mail_from, personalName);
   message.setFrom(address); // 设置邮件发送者的地址
   Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
   //Address toAddress = new InternetAddress("[email protected]");
   message.addRecipient(Message.RecipientType.TO, toAddress);
   Transport.send(message); // 发送邮件
   if(flag.equals("yes"))
   {
   Sql s = new Sql();
   PubDate dates = new PubDate();
   int ids = s.maxID("OA004", "OA004_ID");
   String sql_stra="insert into OA004(OA004_ID,OA004_MODEL_CODE,OA004_APPLY_DATE,OA004_FROM_MAIL,OA004_TO_MAIL,OA004_SUBJECT,OA004_BODY,OA004_STATUS) values (";
   sql_stra+=ids+",'"+modelCode+"',to_date('"+dates.getDate("yyyy-MM-dd HH:mm:ss")+"','yyyy-mm-dd hh24:mi:ss'),'"+mail_from+"','"+mail_to+"','"+mail_subject+"','"+mail_body+"','ok')";
  // System.out.println(sql_stra);
   s.update(sql_stra);
  
   }
   //System.out.println("send ok!");
  } catch (Exception ex) {
  if(flag.equals("yes"))
   {
   Sql s = new Sql();
   PubDate dates = new PubDate();
   int ids = s.maxID("OA004", "OA004_ID");
   String sql_stra="insert into OA004(OA004_ID,OA004_MODEL_CODE,OA004_APPLY_DATE,OA004_FROM_MAIL,OA004_TO_MAIL,OA004_SUBJECT,OA004_BODY,OA004_STATUS,OA004_ERRORS) values (";
   sql_stra+=ids+",'"+modelCode+"',to_date('"+dates.getDate("yyyy-MM-dd HH:mm:ss")+"','yyyy-mm-dd hh24:mi:ss'),'"+mail_from+"','"+mail_to+"','"+mail_subject+"','"+mail_body+"','no','"+ex.getMessage()+"')";
  // System.out.println(sql_stra);
   s.update(sql_stra);
  
   }
   ex.printStackTrace();
  }
 }
  /**
  * 用来进行服务器对用户的认证
  */
 public class Email_Autherticator extends Authenticator {
  public Email_Autherticator() {
   super();
  }  public Email_Autherticator(String user, String pwd) {
   super();
   username = user;
   password = pwd;
  }  public PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(username, password);
  }
 }public String getHost() {
return host;
}public void setHost(String host) {
this.host = host;
}public String getMail_body() {
return mail_body;
}public void setMail_body(String mail_body) {

this.mail_body = mail_body;
}public String getMail_from() {
return mail_from;
}public void setMail_from(String mail_from) {
this.mail_from = mail_from;
}public String getMail_head_name() {
return mail_head_name;
}public void setMail_head_name(String mail_head_name) {
this.mail_head_name = mail_head_name;
}public String getMail_head_value() {
return mail_head_value;
}public void setMail_head_value(String mail_head_value) {
this.mail_head_value = mail_head_value;
}public String getMail_subject() {
return mail_subject;
}public void setMail_subject(String mail_subject) {
this.mail_subject = mail_subject;
}public String getMail_to() {
return mail_to;
}public void setMail_to(String mail_to) {
this.mail_to = mail_to;
}public String getPassword() {
return password;
}public void setPassword(String password) {
this.password = password;
}public String getPersonalName() {
return personalName;
}public void setPersonalName(String personalName) {
this.personalName = personalName;
}public String getUsername() {
return username;
}public void setUsername(String username) {
this.username = username;
}public String getFlag() {
return flag;
}public void setFlag(String flag) {
this.flag = flag;
}public String getModelCode() {
return modelCode;
}public void setModelCode(String modelCode) {
this.modelCode = modelCode;
}}

解决方案 »

  1.   

    自己随便写的一个,已经投入运行,凑合能用,缺点就是不是多线程的   
      package   com.justnorth.tools.csdn;   
        
      import   java.io.*;   
      import   java.util.Properties;   
      import   java.util.Date;   
      import   java.sql.*;   
        
      import   javax.mail.*;   
      import   javax.activation.*;   
      import   javax.mail.internet.*;   
      
      public   class   AutoMailer   
      {   
        
              public   AutoMailer(String   from,String   smtp)   
              {   
                      this.from=from;   
                      this.smtp=smtp;   
                      Properties   properties   =   new   Properties();   
                      properties.put("mail.smtp.host",   smtp);   
                      properties.put("mail.transport.protocol",   "smtp");   
                      //authentication   is   needed   
                      properties.put("mail.smtp.auth",   "false");   
        
                      session   =   Session.getDefaultInstance(properties,   new   Authenticator()   {   
                                              protected   PasswordAuthentication   getPasswordAuthentication()   {   
                                                      return   new   PasswordAuthentication("yourname",   "yourPass");   
                                              }   
                                      });   
              }   
        
              public   void   send(String   toaddrs,   String   subject,   String   body,   File   attach)   
                      throws   MessagingException   
              {   
                      try   
                      {   
                              Message   msg   =   new   MimeMessage(session);   
                              msg.setRecipients(javax.mail.Message.RecipientType.TO,   InternetAddress.parse(toaddrs));   
                              msg.setFrom(new   InternetAddress(from));   
                              MimeBodyPart   mp1   =   new   MimeBodyPart();   
                                
                              //msg.setDataHandler(new   DataHandler(   
              //   new   ByteArrayDataSource(body,   "text/html")));   
                              msg.setText(body);   
                
                              mp1.setText(body);   
                              Multipart   mp   =   new   MimeMultipart();   
                              mp.addBodyPart(mp1);   
                              if(attach   !=   null   &&   attach.exists())   
                              {   
                                      MimeBodyPart   mp2   =   new   MimeBodyPart();   
                                      FileDataSource   fds   =   new   FileDataSource(attach);   
                                      mp2.setDataHandler(new   DataHandler(fds));   
                                      mp2.setFileName(attach.getName());   
                                      mp.addBodyPart(mp2);   
                              }   
                              msg.setSubject(subject);   
                              //msg.setContent(mp);   
                              msg.setSentDate(new   Date());   
                              String   osmtp   =   System.getProperty("mail.smtp.host",   smtp);   
                              System.setProperty("mail.smtp.host",   smtp);   
                              Transport.send(msg);   
                              System.setProperty("mail.smtp.host",   osmtp);   
                      }   
                      catch(Throwable   e)   
                      {   
                              System.out.println(e);   
                              e.printStackTrace();   
                              throw   new   MessagingException(e.toString());   
                      }   
              }   
              String   from;   
              String   smtp;   
              Session   session;   
                
              public   static   void   send(String   urlStr,String     userName,String   password,int   sendcaseID)throws   Exception{   
                      String   driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver";   
                      //String   urlStr="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=crm";   
                      //String   userName="sa";   
                      //String   password="";   
                        
                      Driver   driver   =   (Driver)   Class.forName(driverClassName).newInstance();   
                      DriverManager.registerDriver(driver);   
                      Connection   con   =   DriverManager.getConnection(urlStr,userName,password);   
                      Statement   stmt   =   con.createStatement();   
                      String   sql="select   mailID,   condition   from   sendCase   where   sendcaseID="+sendcaseID;   
                      ResultSet   rs   =   stmt.executeQuery(sql);     
                      String   condition="";   
                      int   mailID=0;   
                      if   (rs.next())   {   
                              condition=rs.getString("condition");   
                              mailID=rs.getInt("mailID");   
                      }   
                      //读取发送mail内容   
                      sql="select   mailTitle,   mailContext   from   mails   where   mailID="+mailID;   
                      rs   =   stmt.executeQuery(sql);     
                      String   mailTitle="";   
                      String   mailContext="";   
                      if   (rs.next())   {   
                              mailTitle=rs.getString("mailTitle");   
                              mailContext=rs.getString("mailContext");   
                      }   
                      //读取发送邮件列表   
                      rs   =   stmt.executeQuery(condition);     
                      //条件sql语句的字段名与邮件内容绑定,而且邮件地址名称必须为email   
                      //读取字段信息   
                      ResultSetMetaData   rsmd   =   rs.getMetaData();   
                      String[]   columnName=new   String[rsmd.getColumnCount()];   
                      for   (int   i=0;i<rsmd.getColumnCount();i++){   
                              columnName[i]=rsmd.getColumnName(i+1);   
                      }   
                      while(rs.next()){   
                              String   sendContext=mailContext;   
                              //对邮件内容中的变量进行替换   
                              for(int   i=0;i<columnName.length;i++){   
                                      sendContext=sendContext.replaceAll("%"+columnName[i]+"%",rs.getString(i+1));   
                              }   
                              //发送邮件   
                              AutoMailer   sender=new   AutoMailer("[email protected]","businesscompass.com");   
                              sender.send(rs.getString("email"),mailTitle,sendContext,null);   
                              System.out.println("just   send   to   "+rs.getString("email"));   
                      }   
                        
              }   
                
              public   static   void   main(String   args[])throws   Exception{   
                      InputStream   is;     
                      if   (args.length>0){   
                              is   =new   FileInputStream(args[0]);   
                      }   
                      else{   
                              is   =new   FileInputStream("mail.properties");   
                      }   
                      Properties   prop   =   new   Properties();   
                      prop.load(is);   
                      String   urlStr=prop.getProperty("url");   
                      String   userName=prop.getProperty("user");   
                      String   password=prop.getProperty("password");   
                      int   sendcaseID=Integer.valueOf(prop.getProperty("sendcaseID")).intValue();   
                        
                      AutoMailer.send(urlStr,userName,password,sendcaseID);   
                        
              }   
      }   
        
      //java   -cp   .;D:/tomcat/webapps/businesscompass/WEB-INF/lib/mail.jar;D:/tomcat/webapps/businesscompass/WEB-INF/lib/activation.jar   com.justnorth.tools.csdn.Mailer   D:\tomcat\webapps\businesscompass\WEB-INF\classes\com\justnorth\tools\csdn\mail.properties  
      

  2.   


    <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="75"   border="0"   align="center"   cellspacing="1"   bgcolor="#006600"   class="black">   
      <tr   bgcolor="#FFFFFF">     
      <td   width="24%">收信人地址:</td>   
      <td   width="76%">   <input   name="to"   type="text"   id="to"></td>   
      </tr>   
      <tr   bgcolor="#FFFFFF">     
      <td>主题:</td>   
      <td>   <input   name="title"   type="text"   id="title"></td>   
      </tr>   
      <tr>     
      <td   height="18"   colspan="2"   bgcolor="#FFFFFF">信件类型   
      <select   name="emailtype"   id="emailtype">   
      <option   value="text/plain"   selected>Text</option>   
      <option   value="text/html">Html</option>   
      </select></td>   
      </tr>   
      <tr>     
      <td   height="53"   colspan="2"   bgcolor="#FFFFFF"><textarea   name="content"   cols="50"   rows="5"   id="content"></textarea></td>   
      </tr>   
      <tr   align="center">     
      <td   colspan="2"   bgcolor="#FFFFFF">附件1(自定义):     
      <input   name="fj1"   type="text"   id="fj1">   
      (输入文本信息)   </td>   
      </tr>   
      <tr   align="center"   valign="bottom">     
      <td   colspan="2"   bgcolor="#FFFFFF">附件2(本地):     
      <input   name="fj2"   type="file"   id="fj2"   size="10"></td>   
      </tr>   
      <tr   align="center">     
      <td   colspan="2"   bgcolor="#FFFFFF">附件3(远程):     
      <input   name="fj3"   type="text"   id="fj3"   value="http://">   
      (输入URL)</td>   
      </tr>   
      <tr   align="center">     
      <td   colspan="2"   bgcolor="#FFFFFF">   <input   type="submit"   name="Submit"   value="发送">     
      <input   type="reset"   name="Submit2"   value="重置"></td>   
      </tr>   
      </table>   
      </form>   
      </body>   
      </html>   
        
        
      处理邮件的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.*"%><!--要发送附件必须引入该库-->   
      <%@   page   import="java.net.*"%><!--要用到URL类-->   
      <html>   
      <head>   
      <meta   http-equiv="Content-Type"   content="text/html;   charset=gb2312">   
      <title>发送成功</title>   
      </head>   
      <body>   
      <%   
      try{   
      String   tto=request.getParameter("to");   
      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");   
        
      Properties   props=new   Properties();   
      props.put("mail.smtp.host","127.0.0.1");   
      props.put("mail.smtp.auth","true");   
      Session   s=Session.getInstance(props);   
      s.setDebug(true);   
        
      MimeMessage   message=new   MimeMessage(s);   
        
      //给消息对象设置发件人/收件人/主题/发信时间   
      InternetAddress   from=new   InternetAddress("[email protected]");   
      message.setFrom(from);   
      InternetAddress   to=new   InternetAddress(tto);   
      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(tfj1,"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("127.0.0.1","xxf","coffee");   
      transport.sendMessage(message,message.getAllRecipients());   
      transport.close();   
      %>   
      <div   align="center">   
      <p><font   color="#FF6600">发送成功!</font></p>   
      <p><a   href="recmail.jsp">去看看我的信箱</a><br>   
      <br>   
      <a   href="index.htm">再发一封</a>   </p>   
      </div>   
      <%   
      }catch(MessagingException   e){   
      out.println(e.toString());   
      }   
      %>   
      </body>   
      </html>
      

  3.   

    public class User_RegisterAction extends Action{
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
    CUserForm userForm = (CUserForm)form;
    UserDao userDao = new UserDao();
    //验证验证码
    HttpSession session=request.getSession();
    String mach=request.getParameter("rand");
    String year=request.getParameter("year");
    String month=request.getParameter("month");
    String day=request.getParameter("day");
    String birth=year+"-"+month+"-"+day ;
    userForm.setUserAge(birth);
    String mach2=(String) session.getAttribute("rand");
    if(!mach.equals(mach2)){
    request.setAttribute("errors", "");
    return mapping.findForward("errors");
    }
    //密码加密
    String password = request.getParameter("userPsw");
    String useremail = request.getParameter("userEmail");
    String username = request.getParameter("userLogonname");
    String userEmailsign = Md5.MD5Encode(username + System.currentTimeMillis()); 
    userForm.sesetUserEmail(useremail);
    userForm.setUserEmailsign(userEmailsign);
    String pswa =Md5.MD5Encode(password);
    userForm.setUserPsw(pswa);
    CUser user=userDao.findByName(userForm.getUserLogonname());
    if(user!=null){
    request.setAttribute("LoginName_repeat", "");
    return mapping.findForward("errors");
    }else{
    int temp=userDao.addUser(userForm);
    if(temp==1){
    HttpSession httpSession = request.getSession();
    httpSession.setAttribute("usern",user);
    // 邮件发送者邮箱用户 
    String SMTPUserName = "";   
    // 邮件发送者邮箱密码 
    String SMTPPassword = ""; 
    // 邮件发送者邮箱SMTP服务器 
    String SMTPServerName = "smtp.163.com"; 
    // 传输类型 
    String TransportType = "smtp"; 
    // 属性
    String SenderEmailAddr = "[email protected]";
    Properties props = new Properties();
    // 存储发送邮件服务器的信息 
        props.put("mail.smtp.host", SMTPServerName); 
        // 同时通过验证 
        props.put("mail.smtp.auth", "true"); 
    //根据属性新建一个邮件会话,null参数是一种Authenticator(验证程序) 对象          Session s = Session.getInstance(props, null);
            // 设置调试标志,要查看经过邮件服务器邮件命令,可以用该方法 
            s.setDebug(false); 
            //由邮件会话新建一个消息对象 
            Message message = new MimeMessage(s); 
            try { 
                // 设置发件人 
                Address from = new InternetAddress(SenderEmailAddr); 
                message.setFrom(from); 
                // 设置收件人 
                Address to = new InternetAddress(useremail); 
                message.setRecipient(Message.RecipientType.TO, to); 
                // 设置主题 
                message.setSubject("test"); 
                // 设置信件内容 
                message.setText("test"); 
                // 设置发信时间 
                message.setSentDate(new Date()); 
                // 存储邮件信息 
                message.saveChanges(); 
                Transport transport = s.getTransport(TransportType); 
                // 要填入你的用户名和密码; 
                transport.connect(SMTPServerName, SMTPUserName, 
                        SMTPPassword); 
                // 发送邮件,其中第二个参数是所有已设好的收件人地址 
                transport.sendMessage(message, message.getAllRecipients()); 
                transport.close(); 
                System.out.println("发送邮件成功!"); 
            } catch (Exception e) { 
                System.out.println(e.getMessage()); 
                System.out.println("发送邮件失败! 原因是" + e.getMessage()); 
            }  return mapping.findForward("sucess");
    }else{
    return mapping.findForward("errors");
    }

    }
    }
      

  4.   

    邮件的正文为文本的话就是是content 的类型就是 text/plain,这个是没有错的。
    楼主的问题,我还真没有遇到过,我之前研究过这一块,建议楼主要解决要看两个地方
    1:javax.mail.internet.MimeBodyPart类
    2:mail\META-INF\mailcap