public static String sendmail(String from,String to,String reply_to,String host,String subject,String body,String filename) 
   { 
    
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.setProperty("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props, new myAuth());    
    try {
        // create a message
        if(from.trim().length()<1) 
         {if(reply_to.trim().length()<1)  {from=to;reply_to=to;}
          else from=reply_to;
         }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address1 = {new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, address1);
        InternetAddress[] address2 = {new InternetAddress(reply_to)};
        msg.setReplyTo(address2);
        
        
        msg.setSubject(subject);        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(body);        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();            // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(new String(fds.getName().getBytes("GBK"),"iso8859-1"));        // create the Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);        // add the Multipart to the message
        msg.setContent(mp);        // set the Date: header
        msg.setSentDate(new java.util.Date());
        
        // send the message
        Transport.send(msg);
        
       }
     catch (Exception e) {e.printStackTrace();return "发送邮件失败:"+e.toString()+"!";} 
     return "邮件发送成功!";
    
    }
    

解决方案 »

  1.   

    public static String sendmail(String from,String to,String reply_to,String host,String subject,String body,String filename) 
       { 
        
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.setProperty("mail.smtp.auth","true");
        Session session = Session.getDefaultInstance(props, new myAuth());    
        try {
            // create a message
            if(from.trim().length()<1) 
             {if(reply_to.trim().length()<1)  {from=to;reply_to=to;}
              else from=reply_to;
             }
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address1 = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address1);
            InternetAddress[] address2 = {new InternetAddress(reply_to)};
            msg.setReplyTo(address2);
            
            
            msg.setSubject(subject);        // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(body);        // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();            // attach the file to the message
            FileDataSource fds = new FileDataSource(filename);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(new String(fds.getName().getBytes("GBK"),"iso8859-1"));        // create the Multipart and its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);        // add the Multipart to the message
            msg.setContent(mp);        // set the Date: header
            msg.setSentDate(new java.util.Date());
            
            // send the message
            Transport.send(msg);
            
           }
         catch (Exception e) {e.printStackTrace();return "发送邮件失败:"+e.toString()+"!";} 
         return "邮件发送成功!";
        
        }
        
      

  2.   

    为什么要用什么Authenticator的类我不太明白你到底要干嘛
      

  3.   

    javahui(阶级斗争要年年讲,月月讲,天天讲。) :我的和你的差不多呀,还是不行,再帮我一把!
    tibetty(laoduan)老兄:指点得有道理!有理想就帮我看看我的程序到底哪里不行?总显示“邮件发送失败!javax.mail.AuthenticationFailedException”。import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.Date;
    import javax.activation.*;
    import java.io.*;
    //import com.me.util.*;
    public class sendMail { private MimeMessage mimeMsg; //MIME邮件对象
    private Session session; //邮件会话对象
    private static Properties props; //系统属性
    private boolean needAuth = true; //smtp是否需要认证 
    private String username = ""; //smtp认证用户名和密码
    private String password = "";
    private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
        private Email_Autherticatorbean zxzAuthen;
    public sendMail(String smtp){
    setSmtpHost(smtp);
    createMimeMessage();
    }

    public void setSmtpHost(String hostName) {
    System.out.println("设置系统属性:mail.smtp.host = "+hostName);
    if(props == null)props = System.getProperties(); //获得系统属性对象

    props.put("mail.smtp.host",hostName); //设置SMTP主机
    }

    public boolean createMimeMessage()
    {
    try{
    System.out.println("准备获取邮件会话对象!");
    }
    catch(Exception e){
    System.err.println("获取邮件会话对象时发生错误!"+e);
    return false;
    }

    System.out.println("准备创建MIME邮件对象!");
    try{
    mimeMsg = new MimeMessage(session); //创建MIME邮件对象
    mp = new MimeMultipart();
    return true;
    }
    catch(Exception e){
    System.err.println("创建MIME邮件对象失败!"+e);
    return false;
    }
    }

    public void setNeedAuth(boolean need) {
    System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
    if(props == null)props = System.getProperties();

    if(need){
    props.put("mail.smtp.auth","true");
    }else{
    props.put("mail.smtp.auth","false");
    }
    }

    public void setNamePass(String name,String pass) {
    username = name;
    password = pass;
    zxzAuthen= new Email_Autherticatorbean(username,password);
    }
    public boolean setSubject(String mailSubject) {
    System.out.println("设置邮件主题!");
    try{
    mimeMsg.setSubject(mailSubject);
    return true;
    }
    catch(Exception e) {
    System.err.println("设置邮件主题发生错误!");
    return false;
    }
    }

    public boolean setBody(String mailBody) {
    try{
    BodyPart bp = new MimeBodyPart();
    bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+mailBody,"text/html;charset=GB2312");
    mp.addBodyPart(bp);
    return true;
    }
    catch(Exception e){
    System.err.println("设置邮件正文时发生错误!"+e);
    return false;
    }
    }
    public boolean addFileAffix(String filename) {

    System.out.println("增加邮件附件:"+filename);

    try{
    BodyPart bp = new MimeBodyPart();
    FileDataSource fileds = new FileDataSource(filename);
    bp.setDataHandler(new DataHandler(fileds));
    bp.setFileName(fileds.getName());

    mp.addBodyPart(bp);

    return true;
    }
    catch(Exception e){
    System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
    return false;
    }
    }
    public boolean setFrom(String from) {
    System.out.println("设置发信人!");
    try{
    mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
    return true;
    }
    catch(Exception e)
    { return false; }
    }

    public boolean setTo(String to){
    if(to == null)return false;

    try{
    mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
    return true;
    }
    catch(Exception e)
    { return false; }

    }
    public boolean setCopyTo(String copyto)
    {
    if(copyto == null)return false;
    try{
    mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
    return true;
    }
    catch(Exception e)
    { return false; }
    }

    public boolean sendout()
    {
    try{
    mimeMsg.setContent(mp);
    mimeMsg.saveChanges();
    System.out.println("正在发送邮件....");
    session=Session.getInstance(props,zxzAuthen);
    Transport transport = session.getTransport("smtp");
    transport.connect((String)props.get("mail.smtp.host"),username,password);
    transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
    System.out.println("发送邮件成功!");
    transport.close();

    return true;
    }
    catch(Exception e)
    {
    System.err.println("邮件发送失败!"+e);
    return false;
    }
    }
    public static void main(String[] args) {

    String mailbody = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+
    "<div align=center><a href=http://www.csdn.net> csdn </a></div>";

    sendMail themail = new sendMail("smtp.yeah.net");          themail.setNeedAuth(true);
    if(themail.setSubject("测试邮件") == false) return;
    if(themail.setBody(mailbody) == false) return;
                       //改为接收邮件地址即可
    if(themail.setTo("[email protected]") == false) return;
                       //改为发送邮件地址即可
    if(themail.setFrom("&&&&&&&@yeah.net") == false) return;
    if(themail.addFileAffix("d:\\mail.txt") == false) return;
    themail.setNamePass("&&&&&&&","******");
             if(themail.sendout() == false) return; 
    } public static class Email_Autherticatorbean  extends Authenticator
    {
    private String m_username = null;
    private String m_userpass = null;
    public void setUsername(String username)
    {
    m_username = username;
    }
    public void setUserpass(String userpass)
    {
    m_userpass = userpass;
    }
    public Email_Autherticatorbean(String username, String userpass)
    {
    super();
    setUsername(username);
    setUserpass(userpass);

    }
    public PasswordAuthentication getPasswordAuthentication()
    {
    return new PasswordAuthentication(m_username,m_userpass);
    }
    }
    }
      

  4.   

    你的构造函数:
    public sendMail(String smtp){
    setSmtpHost(smtp);
    createMimeMessage();
    }createMimeMessage();方法执行中
    mimeMsg = new MimeMessage(session); //创建MIME邮件对象session是null。当然会失败了。
      

  5.   

    兄弟,下面是我在一个商务网站的一段代码看一下吧
    try 
          {
    Properties props = new Properties();
    props = new Properties();
    props.put("mail.smtp.host", mail_smtp_host);
    props.setProperty("mail.transport.protocol","smtp");
    props.setProperty("mail.smtp.auth","true");
    Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(mail_from);
    message.setFrom(from);
    InternetAddress to = new InternetAddress(email);
    message.addRecipient(Message.RecipientType.TO,to);
    message.setSubject(subject); MimeBodyPart messageBodyPart =new MimeBodyPart();
    //设置邮件内容,构建程序段如下:
    messageBodyPart.setText(content); Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart); Transport transport = s.getTransport("smtp");    //注意是smtp服务器
    transport.connect(mail_smtp_host,mail_account_username,mail_account_password);
    transport.sendMessage(message,message.getAllRecipients());
    transport.close();
     }
     catch(Exception e) 
     {
    //out.print("<br><br><div align = center>现在不能发送邮件,请稍后再发送!</div>");
     }另外要在一个头文件中写:
    //[.:邮箱参数设置:.]
    String mail_smtp_host = "smtp.163.net";            //发邮件的主机
    String mail_account_username = "";        //邮箱帐号名
    String mail_account_password = "";            //邮箱密码
    String mail_from = "[email protected]";            //邮箱地址
      

  6.   

    嗯..不错耶...马上就要用到javamail了///
      

  7.   

    我帮你
    public boolean sendEmail(MemberDTO memberDTO, InboxDTO emailDTO) throws java.rmi.RemoteException {
            Session session = null;
            Message msg = null;
            String error = null;
            System.out.println("sendEmail(InboxDTO) in com.lanxin.email.ejb.session.email");
            System.out.println(BusinessFactory.getEmailsession());
            try{
                session = BusinessFactory.getEmailsession();
                Properties mailProps = new Properties();
                mailProps.put("mail.transport.protocol", "smtp");
                System.out.println("memberDTO.getEmailStmp() ===========" + memberDTO.getEmailStmp());
                mailProps.put("mail.host", memberDTO.getEmailStmp());
                mailProps.put("mail.user", memberDTO.getEamil().substring(0,emailDTO.getFromid().lastIndexOf("@")));
                System.out.println("mail.user===============" +  memberDTO.getEamil().substring(0,emailDTO.getFromid().lastIndexOf("@")));
                //mailProps.put("mail.from", emailDTO.getFromid());
                mailProps.put("mail.from",emailDTO.getFromid());
                mailProps.put("mail.debug", "true");
                mailProps.put("mail.smtp.auth","true");
                MailAuthenticator mailAuth = new MailAuthenticator();
                System.out.println("memberDTO.getSmtpUser() ========" + memberDTO.getSmtpUser());
                System.out.println("memberDTO.getSmtpPwd() ==============" + memberDTO.getSmtpPwd());
                mailAuth.setUser(memberDTO.getSmtpUser());
                mailAuth.setPassword(memberDTO.getSmtpPwd());
                System.out.println("amilAuth ========" + mailAuth);
                session = session.getInstance(mailProps, mailAuth);
                System.out.println("session ===========" + session);
                msg = new MimeMessage(session);
                msg.setFrom();
                String to = emailDTO.getUserid();
                String subject = emailDTO.getTitle();
                msg.setRecipients(Message.RecipientType.TO,
                                  InternetAddress.parse(to, false));
                msg.setSubject(subject);
                msg.setText(emailDTO.getContent());
                msg.saveChanges();
                Transport auth = session.getTransport();
                auth.connect();
                auth.sendMessage(msg, msg.getAllRecipients());
                auth.close();
                System.out.println();
                error = "send successed!";
                return true;
            }catch(Exception e){
                e.printStackTrace();
                System.out.println("Warning,Sending Email is wrong!");
                return false;
            }
        }
      

  8.   

    import javax.mail.Authenticator;
    import javax.mail.*;public class MailAuthenticator extends Authenticator {
        private String user;
        private String password;    public void setUser(String user){
            this.user = user;
        }
        public void setPassword(String password){
            this.password = password;
        }
        public String getUser(){
            return this.user;
        }
        public String getPassword(){
            return this.password;
        }
       /*
        */
        public PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication(user, password);
        }}
      

  9.   

    session = BusinessFactory.getEmailsession();
    是在weblogic中配了mail session