【问题标题】:Unable to send email in background though there is no exception尽管没有例外,但无法在后台发送电子邮件
【发布时间】:2016-01-29 20:11:01
【问题描述】:

我正在尝试通过基于SO answer 的按钮单击从我的Android 应用程序在后台发送电子邮件。 我检查我是否收到了电子邮件,但没有。

这是按钮的点击

 @Override
        public void onClick(View view) {
            //databaseHelper.delete();
            if(!(fromLocation.getText().toString().equals(destination.getText().toString())))
            {
                databaseHelper.saveBookingDetails(sessionManager.getUserEmail(),SelectedDateView.getText().toString(), timePicker.getText().toString(),vehiclePick.getSelectedItem().toString(), fromLocation.getText().toString(), destination.getText().toString());
                try {
                    GMailSender sender = new GMailSender("from@gmail.com", "password");
                    sender.sendMail("This is Subject",
                            "This is Body",
                            "from@gmail.com",
                            "to@outlook.com");
                } catch (Exception e) {
                    Log.e("SendMail", e.getMessage(), e);
                }

            }else Toast.makeText(getActivity(), " Destination & Pickup Location cannot be same", Toast.LENGTH_LONG).show();

        }
    });

另外两个类GMailSender,JSSEProvider我刚刚复制使用了。我也添加了 3 个 jar 文件。我应该使用 AsyncTask 吗?我究竟做错了什么?也许 gmail 不允许我登录到我的应用程序发送邮件?

【问题讨论】:

    标签: android email


    【解决方案1】:

    为不太安全的应用开启 Access https://www.google.com/settings/security/lesssecureapps 在上面提到的链接中再试一次

    【讨论】:

    • 我应该只下载和导入吗?
    【解决方案2】:

    如果您从 gmail 发送,那么您必须允许不太安全的权限。

    https://support.google.com/accounts/answer/6010255?hl=en

    【讨论】:

      【解决方案3】:

      您可以使用此代码 MailSender.java

       import java.io.File;
       import java.io.UnsupportedEncodingException;
       import java.util.Properties;
      
      import javax.activation.DataHandler;
      import javax.activation.DataSource;
      import javax.activation.FileDataSource;
      import javax.mail.BodyPart;
      import javax.mail.Message;
      import javax.mail.MessagingException;
      import javax.mail.Multipart;
      import javax.mail.PasswordAuthentication;
      import javax.mail.Session;
      import javax.mail.Transport;
      import javax.mail.internet.InternetAddress;
      import javax.mail.internet.MimeBodyPart;
      import javax.mail.internet.MimeMessage;
      import javax.mail.internet.MimeMultipart;
      
      import android.os.Environment;
      import android.text.Html;
      import android.util.Log;
      
      public class MailSender extends javax.mail.Authenticator {   
          private String mailhost = "smtp.gmail.com";   
      
          private String password;   
          private Session session;   
          String to="";
          String sub="";
          String msg="";
          String file1="";
          String file2="";
          String user="";
          String pass="";
      
      
          public MailSender(String to, String sub, String msg,String file1, String file2,String user, String pass) {
              this.to=to;
              this.sub=sub;
              this.msg=msg;
              this.file1=file1;
              this.file2=file2;
              this.user=user;
              this.pass=pass;
          // TODO Auto-generated constructor stub
      }
      
      
          public MailSender(String user, String pass)
          {
              this.user=user;
              this.pass=pass;
              // TODO Auto-generated constructor stub
          }
      
      
          public synchronized void sendMail() {   
      
              File mediaStorageDir = Environment.getExternalStorageDirectory();
              Properties props = new Properties();
              props.put("mail.smtp.host", "smtp.gmail.com");
              props.put("mail.smtp.socketFactory.port", "465");
              props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
              props.put("mail.smtp.auth", "true");
              props.put("mail.smtp.port", "465");
      
              if(user.trim().length()!=0 || pass.trim().length()!=0)
              {
      
      
              Session s1 = Session.getInstance(props,new javax.mail.Authenticator() {
                  protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(user,pass);//change accordingly
                  }
                  });
              try {
                  MimeMessage message = new MimeMessage(s1);
                  InternetAddress fromAddress=new InternetAddress(user,"set your from text");
                  message.setFrom(fromAddress);//change accordingly
      
                  message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
                  message.setSubject(sub);
      
                  // message.setContent("<h1>This is actual message</h1>","text/html" );
                  BodyPart messageBodyPart1 = new MimeBodyPart();  
                  messageBodyPart1.setContent(msg,"text/html");
                   Multipart multipart = new MimeMultipart();  
                  multipart.addBodyPart(messageBodyPart1);  
                  MimeBodyPart messageBodyPart2 = null;
                  MimeBodyPart messageBodyPart3= null;
                  if(file1.trim().length()>0)
                  {
                       messageBodyPart2 = new MimeBodyPart();  
                      String filename =file1;//change accordingly  
                      DataSource source = new FileDataSource(filename);  
                      messageBodyPart2.setDataHandler(new DataHandler(source));  
                      messageBodyPart2.setFileName(filename);  
                      multipart.addBodyPart(messageBodyPart2);  
                  }
      
                  if(file2.trim().length()>0)
                  {
                       messageBodyPart3 = new MimeBodyPart();  
                      String filename =file2;//change accordingly  
                      DataSource source = new FileDataSource(filename);  
                      messageBodyPart3.setDataHandler(new DataHandler(source));  
                      messageBodyPart3.setFileName(filename);  
                      multipart.addBodyPart(messageBodyPart3);  
                  }
      
      
                  message.setContent(multipart );  
      
                  Transport.send(message);
      
                  //Log.i("Status", "Message Sent Successfully");
      
      
                  } catch (MessagingException e) 
                  {
                      throw new RuntimeException(e);
                  } catch (UnsupportedEncodingException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
              else
              {
                  //Log.i("mail", user+pass);
              }
          }   
      
      
          protected PasswordAuthentication getPasswordAuthentication() {   
              return new PasswordAuthentication(user, password);   
          }   
      
      
      }  
      

      在你的 onclick 方法中调用 asyntask 之类的

       RetrieveFeedTask eft=new RetrieveFeedTask(receiver_email,sub,header,msg,"");
                          eft.execute();
      

      在 MainActivity 中添加 RetrieveFeedTask1 作为内部类并替换用户名和密码的值

          class RetrieveFeedTask extends AsyncTask<String, Void, Void> {
      
          private Exception exception;
          String to="";
          String sub="hii";
          String msg="";
          String file1="";
          String file2="";
          String header="";
          String password="";
         // String user="";
          SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
      String user="from@gmail.com";//your sender email id
          String pass="password";//sender password
          //  String reversepass = new StringBuffer(pass).reverse().toString();
      
      
          //String text = new String(pass, "UTF-8");
      
          public RetrieveFeedTask(String to, String sub, String header,String msg,String file1) {
              this.to=to;
              this.sub=sub;
              this.header=header;
              this.msg=msg;
              this.file1=file1;
      
              // TODO Auto-generated constructor stub
          }
      
      
          public RetrieveFeedTask(String to, String sub, String header,String msg, String file1, String file2) {
              this.to=to;
              this.sub=sub;
              this.header=header;
              this.msg=msg;
              this.file1=file1;
              this.file2=file2;
              // TODO Auto-generated constructor stub
          }
      
      
          protected Void doInBackground(String... urls) {
      
              MailSender ms=new MailSender(to,sub,header+msg,file1,file2,user,pass);
              ms.sendMail();
              //ms.sendStastical(stastical_email, sub, header+msg);
              return null;
      
          }
      
          @Override
          protected void onPostExecute(Void result) {
           //   Log.d("postexecute", "p execute");
           //   pDialog.dismiss();
              Toast.makeText(getApplicationContext(), "Mail Sent Successfully", Toast.LENGTH_LONG ).show();
           File newfile=new File(file1);
           newfile.delete();
           File newfile1=new File(file2);
           newfile1.delete();
      
          }
      
           @Override
              protected void onPreExecute() {
                  super.onPreExecute();
      
                  Toast.makeText(getApplicationContext(), "Please wait while sending email", Toast.LENGTH_LONG).show();
              }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-28
        • 2016-06-16
        • 2021-04-17
        • 2011-09-13
        • 1970-01-01
        • 2015-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多