虽然没有例外,但无法在后台发送电子邮件

时间:2016-01-29 11:39:42

标签: android email

我正试图通过基于SO answer的按钮点击我的Android应用程序发送背景信息。 我检查一下我是否收到了电子邮件,但没有。

这是按钮的onclick

 @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();

        }
    });

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您可以使用此代码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 like

 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();
        }

}