使用javamail发送邮件会引发错误

时间:2012-08-30 17:50:36

标签: java android smtp imap javamail

我有两个活动,一个是使用Imap接收电子邮件,另一个是使用SMTP发送电子邮件。发送电子邮件活动的按钮位于“接收电子邮件”活动中,因此“接收电子邮件活动”必须在“发送电子邮件活动”之前运行..

我的问题是我一直在说一个例外 Could not connect to SMTP host: localhost, port: 25

Transport.send(new_message)

但是,如果我在没有先调用接收电子邮件活动的情况下运行相同的活动,那么它的运行没有任何问题。 有人可以帮我解释为什么会这样吗?

这是代码 RecieveEmail异步任务(完整的活动代码太长)

 try{


               Properties props = new Properties();
               props.setProperty( "mail.imaps.socketFactory.class", "com.X509TrustAll.DummySSLSocketFactory" );
               Log.v("EmailList", "Stting properties");

              // Get the default Session object.
              session = Session.getDefaultInstance(props, null);
              Log.v("EmailList", "Geting Default Instance");

              // Get a Store object that implements the specified protocol.
              store = session.getStore("imaps");
              Log.v("EmailList", "Getting Sesion");

              //Connect to the current host using the specified username and password.
              Log.v("EmailList", "Connecting...");
              store.connect(host,port, user, password);
              Log.v("EmailList", "Connected");

              //Create a Folder object corresponding to the given name.
              Folder[] folders = store.getDefaultFolder().list("*");
              Log.v("EmailList", "Got Folder List");
              folder =  folders[5];



              // Open the Folder.
              Log.v("EmailList", "Opening Folder");
              folder.open(Folder.READ_ONLY);

              Log.v("EmailList", "Getting Messages");
              messages = folder.getMessages();

              Log.v("EmailList", "Got Messages");


          } catch (Exception e){

              Log.v("EmailList", "Exception");

          }
        }

              for (int i = lastMessageNumber -1;  i >= interateUpto; i--) {

                  Log.v("EmailRecieve", "Email no. " + Integer.toString(i));

                  javax.mail.Address[] froms = messages[i].getFrom();
                  String emailAdress = froms == null ? null : ((InternetAddress) froms[0]).getAddress();


                  FromAsync.add(emailAdress);

                  SubjectAsync.add(messages[i].getSubject());

                  SentDateAsync.add(messages[i].getSentDate().toString());


                  Part part = messages[i];

                  checkAttachments(part);



                  if (messages[i].isSet(Flag.SEEN)){

                      SeenAsync.add("true");

                  }else{

                      SeenAsync.add("false");

                  }


              }



              lastMessageNumber = lastMessageNumber - 19;   //new last number is stored

              folder.close(false);
              store.close();

        } catch (Exception e){

                  Log.v("EmailList", "Exception");

        }



      Log.v("EmailList", "Retrieve Email Finished");



        return null;

    }

以下是发送电子邮件的代码(再次完整代码太长,所以我只发布相关内容,即UI等未发布

@Override
    protected Void doInBackground(Void... arg0) {

        //Recipient's email ID needs to be mentioned.
          String to = To.getText().toString();

          // Sender's email ID needs to be mentioned
          String from = "foobar@foobar.hehe";

          // The Host
          String smtphost = "www.isleworthsyon.hounslow.sch.uk";

          // Get system properties
          Properties smtpproperties = System.getProperties();

          // Setup mail server
          smtpproperties.setProperty("mail.smtp.host", smtphost);

          // Get the default Session object.
          Session smtpsession = Session.getDefaultInstance(smtpproperties);

          try{
             MimeMessage new_message = new MimeMessage(smtpsession);

             // Set From:
             new_message.setFrom(new InternetAddress(from));

             // Set To:
             new_message.addRecipient(Message.RecipientType.TO,
                                      new InternetAddress(to));

             // Set Subject: 
             new_message.setSubject(Subject.getText().toString());

             if (hasAttachment == true){

                 // Create the message part 
                 BodyPart messageBodyPart = new MimeBodyPart();

                 // Fill the message
                 messageBodyPart.setText(Body.getText().toString());

                 // Create a multipar message
                 Multipart multipart = new MimeMultipart();

                 // Set text message part
                 multipart.addBodyPart(messageBodyPart);

                 // Iterating over all Attachments    
                 for (int i=0; i < attachmentFiles.size(); i++){

                    if (attachmentFiles.get(i).equals("null") != true)    {

                         messageBodyPart = new MimeBodyPart();
                         String filename = attachmentFiles.get(i);
                         FileDataSource source = new FileDataSource(filename);
                         messageBodyPart.setDataHandler(new DataHandler(source));
                         messageBodyPart.setFileName(source.getName());
                         multipart.addBodyPart(messageBodyPart);

                    }
                 }


                 new_message.setContent(multipart);

             }else{

                 // Set Body if not attaching anything
                 new_message.setText(Body.getText().toString());

             }

             // Send message
             Transport.send(new_message);
             sendingSuccesfull = true;
          }catch (MessagingException mex) {
             sendingSuccesfull = false;
             Log.v("Email Compose", "Message Sending Failed, Details: " + mex.getMessage());

          }

        return null;
    }

1 个答案:

答案 0 :(得分:1)

尝试清理these common mistakes,看看是否能解决问题。