2015-01-13 4 views
0

У меня возникли некоторые проблемы при отправке письма электронной почты Gmail, которое я использую в своем приложении.Не удается отправить письмо в Gmail с помощью API JavaMail

Я использую JavaMail Api, чтобы отправить электронное письмо.

Когда я нажимаю кнопку «Отправить», отображается сообщение «Сообщение успеха» в методе onPostExecute, но новое письмо не отправляется в Gmail ID, который я использую в программе.

Мне нужна помощь!

Мой код ниже:

public class GmailSender extends Authenticator { 
    private String mailhost = "smtp.gmail.com"; 
    private String user; 
    private String password; 
    private Session session; 
    static { 
     Security.addProvider(new android.readnews.support.JSSEProvider()); 
    } 

    public GmailSender(String user, String password) { 
     this.user = user; 
     this.password = password; 

     Properties props = new Properties(); 
     props.setProperty("mail.transport.protocol", "smtp"); 
     props.setProperty("mail.host", mailhost); 
     props.put("mail.smtp.auth", "true"); 
     props.put("mail.smtp.port", "465"); 
     props.put("mail.smtp.socketFactory.port", "465"); 
     props.put("mail.smtp.socketFactory.class", 
       "javax.net.ssl.SSLSocketFactory"); 
     props.put("mail.smtp.socketFactory.fallback", "false"); 
     props.setProperty("mail.smtp.quitwait", "false"); 

     session = Session.getDefaultInstance(props, this); 
    } 

    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(user, password); 
    } 

    public synchronized void sendMail(String subject, String body, 
      String sender, String recipients) throws Exception { 
     try { 
      MimeMessage message = new MimeMessage(session); 
      DataHandler handler = new DataHandler(new ByteArrayDataSource(
        body.getBytes(), "text/plain")); 
      message.setSender(new InternetAddress(sender)); 
      message.setSubject(subject); 
      message.setDataHandler(handler); 
      if (recipients.indexOf(',') > 0) { 
       message.setRecipients(Message.RecipientType.TO, 
         InternetAddress.parse(recipients)); 
      } else { 
       message.setRecipient(Message.RecipientType.TO, 
         new InternetAddress(recipients)); 
      } 
      Transport.send(message); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public class ByteArrayDataSource implements DataSource { 
     private byte[] data; 
     private String type; 

     public ByteArrayDataSource(byte[] data, String type) { 
      super(); 
      this.data = data; 
      this.type = type; 
     } 

     public ByteArrayDataSource(byte[] data) { 
      super(); 
      this.data = data; 
     } 

     public void setType(String type) { 
      this.type = type; 
     } 

     public String getContentType() { 
      if (type == null) 
       return "application/octet-stream"; 
      else 
       return type; 
     } 

     public InputStream getInputStream() throws IOException { 
      return new ByteArrayInputStream(data); 
     } 

     public String getName() { 
      return "ByteArrayDataSource"; 
     } 

     public OutputStream getOutputStream() throws IOException { 
      throw new IOException("Not Supported"); 
     } 
    } 
} 

И

public class SendEmailFragment extends Fragment implements OnClickListener { 

    Context mContext = null; 
    Session session = null; 
    ProgressDialog pDialog = null; 
    EditText edtYourEmail, edtSubjectEmail, edtBodyEmail; 
    final String myEmail = "[email protected]"; 
    final String myPass = "abcxyz"; 
    String yourEmail = ""; 
    String Subject = ""; 
    String BodyEmail = ""; 
    GmailSender sender; 

    public SendEmailFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.sendemail_layout, container, 
       false); 
     mContext = container.getContext(); 
     ImageButton btnSendMail = (ImageButton) rootView 
       .findViewById(R.id.buttonSend); 
     edtYourEmail = (EditText) rootView.findViewById(R.id.tv_MailFromBox); 
     edtSubjectEmail = (EditText) rootView 
       .findViewById(R.id.editTextSubject); 
     edtBodyEmail = (EditText) rootView.findViewById(R.id.editMessage); 
     btnSendMail.setOnClickListener(this); 
     return rootView; 
    } 

    @Override 
    public void onClick(View view) { 
     yourEmail = edtYourEmail.getText().toString().trim(); 
     Subject = edtSubjectEmail.getText().toString().trim(); 
     BodyEmail = edtBodyEmail.getText().toString(); 
     pDialog = ProgressDialog.show(mContext, "", "Sending Mail...", true); 

     SendMail sendmailTask = new SendMail(); 
     sendmailTask.execute(); 
    } 



class SendMail extends AsyncTask<Void, Void, Boolean> { 

     @Override 
     protected Boolean doInBackground(Void... arg0) { 
      try { 
       sender = new GmailSender(myEmail, myPass); 
       sender.sendMail(Subject, BodyEmail, myEmail, yourEmail); 
       return true; 
      } catch (Exception e) { 
       Log.i("abc ", "abc " + e.getMessage()); 
       e.printStackTrace(); 
       return false; 
      } 

     } 

     @Override 
     protected void onPostExecute(Boolean result) { 
      if (result == true) { 
       pDialog.dismiss(); 
       edtYourEmail.setText(""); 
       edtSubjectEmail.setText(""); 
       edtBodyEmail.setText(""); 
       Toast.makeText(mContext, "Sending success", Toast.LENGTH_SHORT) 
         .show(); 
      } else { 
       Toast.makeText(mContext, "Sending failure", Toast.LENGTH_SHORT) 
       .show(); 
      } 
      super.onPostExecute(result); 
     } 
    } 
} 

Logcat

01-13 15:35:15.697: W/System.err(1394): javax.mail.AuthenticationFailedException 
01-13 15:35:15.697: W/System.err(1394):  at javax.mail.Service.connect(Service.java:319) 
01-13 15:35:15.697: W/System.err(1394):  at javax.mail.Service.connect(Service.java:169) 
01-13 15:35:15.697: W/System.err(1394):  at javax.mail.Service.connect(Service.java:118) 
01-13 15:35:15.697: W/System.err(1394):  at javax.mail.Transport.send0(Transport.java:188) 
01-13 15:35:15.697: W/System.err(1394):  at javax.mail.Transport.send(Transport.java:118) 
01-13 15:35:15.697: W/System.err(1394):  at android.readnews.support.GmailSender.sendMail(GmailSender.java:67) 
01-13 15:35:15.697: W/System.err(1394):  at android.readnews.main.SendEmailFragment$SendMail.doInBackground(SendEmailFragment.java:93) 
01-13 15:35:15.697: W/System.err(1394):  at android.readnews.main.SendEmailFragment$SendMail.doInBackground(SendEmailFragment.java:1) 
01-13 15:35:15.697: W/System.err(1394):  at android.os.AsyncTask$2.call(AsyncTask.java:287) 
01-13 15:35:15.697: W/System.err(1394):  at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
01-13 15:35:15.697: W/System.err(1394):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
01-13 15:35:15.697: W/System.err(1394):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
01-13 15:35:15.697: W/System.err(1394):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
01-13 15:35:15.697: W/System.err(1394):  at java.lang.Thread.run(Thread.java:856) 
01-13 15:35:15.733: W/InputMethodManagerService(397): Window already focused, ignoring focus gain of: [email protected] attribute=null, token = [email protected] 
01-13 15:40:25.134: W/ThrottleService(397): unable to find stats for iface rmnet0 
+0

Вы видите ошибки в журнале? Не странно, что вы получаете сообщение «отправка успеха», так как вы ловите и проглатываете все исключения в методе 'doInBackground'. Или, по крайней мере, вернуть ненулевой результат в блок try, чтобы увидеть, действительно ли это удалось. –

+0

@ Zoltán i update выше –

+0

Для быстрого решения напечатайте сообщение об исключении (например, 'System.out.println (e.getMessage())'), чтобы быстро узнать, почему аутентификация не удалась, но я предлагаю вам выполнить ошибку как это предлагается в этом ответе: http://stackoverflow.com/a/7133284/900130 –

ответ

0

Вы не должны все socket factory stuff, начните с очистки, что и ваши другие common mistakes. Вам не нужен ваш ByteArrayDataSource since it's included with JavaMail. Затем следуйте этим Gmail instructions и debugging tips. Возможно, вам понадобится enable support for less secure apps. OAuth2 support также может быть полезно.

+0

Я проверю его. Спасибо за помощь :) –

Смежные вопросы