微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android 发送电子邮件验证码在其他设备上不起作用

如何解决Android 发送电子邮件验证码在其他设备上不起作用

我们正在制作一个应用程序,需要用户输入该应用程序将发送的验证码,它对我有用,但是当我将 apk/文件提供给我的朋友并要求他们注册时,他们无法收到验证码,它给他们这个错误“D/错误:singingMailError534-5.7.14

我尝试了以下解决方案: Gmail returns 534-5.7.14 Please log in via your web browser 但是还是不行,别人收不到邮件,只有我能收到。

谢谢大家。

这是我的代码GMailSender.Java

public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;

static {
    Security.addProvider(new JSSEProvider());
}

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

    String prot = "smtp";
    Properties props = System.getProperties();
    props.put("mail." + prot + ".host",mailhost);
    props.put("mail." + prot + ".auth","true");
    props.put("mail." + prot + ".starttls.enable","true");
    props.put("mail." + prot + ".port","587");
    props.put("mail." + prot + ".ssl.enable","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){
        Log.d("Error","sendingMailError"+ e.getMessage());
    }
}

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

}

AccountRegisterVerification.java

public class AccountRegisterVerification extends AppCompatActivity {

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private AppGlobalClass globalVariable;

private ConstraintLayout NoInternetCL;

private Handler handler = new Handler();
private Runnable runnable;

private Button registerBtn,regverResendBT;
String userCode,userpassword,useremail,userfullname;
String user= "mentalhealthue@gmail.com";
String password = "Markchristianpogi1";
GMailSender sender;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestwindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
    getSupportActionBar().hide(); // hide the title bar
    setContentView(R.layout.activity_account_register_verification);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    NoInternetCL = findViewById(R.id.NoInternetCL);
    registerBtn = findViewById(R.id.regverSignupBT);
    regverResendBT = findViewById(R.id.regverResendBT);

    sender = new GMailSender(user,password);

    Intent intent = getIntent();
    userfullname = intent.getStringExtra("Name");
    useremail = intent.getStringExtra("Email").toupperCase();
    userpassword = intent.getStringExtra("Password");
    userCode = intent.getStringExtra("Code");
    globalVariable = (AppGlobalClass) getApplicationContext();
    Controls();
}

private void Controls(){

    registerBtn.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isNetworkAvailable()){
                DocumentReference UserDR = db.collection("Accounts").document(useremail);
                UserDR.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if(task.isSuccessful()){
                            DocumentSnapshot FetchedUser = task.getResult();
                            if (!FetchedUser.exists()){
                                EditText verificationCode = (EditText) findViewById(R.id.verificationCodeET);
                                if (verificationCode.getText().toString().equals(userCode)) {
                                    final Date currentTime = Calendar.getInstance().getTime();
                                    Map<String,Object> NewAccount = new HashMap<String,Object>();
                                    NewAccount.put("Email",useremail);
                                    db.collection("Accounts").document(useremail).set(NewAccount);
                                    Map<String,Object> NewAccountAuthentication = new HashMap<String,Object>();
                                    NewAccountAuthentication.put("Name",userfullname);
                                    NewAccountAuthentication.put("Email",useremail);
                                    NewAccountAuthentication.put("Password",userpassword);
                                    NewAccountAuthentication.put("DateCreated",currentTime);
                                    NewAccountAuthentication.put("Nickname","");
                                    NewAccountAuthentication.put("ProfilePictureURL","");
                                    db.collection("Accounts/" + useremail + "/information").document("Authentication").set(NewAccountAuthentication);

                                    Map<String,Object> NewAccountinformation = new HashMap<String,Object>();
                                    NewAccountinformation.put("OnlineCommunity","Allowed");
                                    db.collection("Accounts/" + useremail + "/information").document("Status").set(NewAccountinformation);

                                    Toast.makeText(getApplicationContext(),"Registration Success",Toast.LENGTH_SHORT).show();

                                    globalVariable.setName(userfullname);
                                    globalVariable.setEmail(useremail);
                                    globalVariable.setPassword(userpassword);

                                    Intent intent = new Intent(AccountRegisterVerification.this,AccountSetup.class);
                                    startActivity(intent);
                                }
                                else {
                                    Toast.makeText(getApplicationContext(),"Invalid Verification Code",Toast.LENGTH_SHORT).show();
                                }
                            }
                            else{
                                EditText verificationCode = findViewById(R.id.verificationCodeET);
                                if (verificationCode.getText().toString().equals(userCode)) {
                                    Intent intent = new Intent(AccountRegisterVerification.this,Login.class);
                                    startActivity(intent);
                                }
                            }
                        }
                    }
                });
            }
            else{
                Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_SHORT).show();
            }
        }
    });

    regverResendBT.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SendCode();
        }
    });

}

private void SendCode(){

    String letters = "ABCDEFGHIJKLMnopQRSTUVWXYZ";
    String number = "123456789";
    char[] alphanumberic = (letters+letters.toupperCase()+number).tochararray();
    StringBuilder result = new StringBuilder();
    for (int i = 0; i <=6; i++){
        result.append(alphanumberic[new Random().nextInt(alphanumberic.length)]);
    }
    userCode = result.toString();

    new MyAsyncclass().execute();
}

class MyAsyncclass extends AsyncTask<Void,Void,Void> {

    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = new ProgressDialog(AccountRegisterVerification.this);
        pDialog.setMessage("Please wait...");
        pDialog.show();

    }

    @Override

    protected Void doInBackground(Void... mApi) {
        try {
            // Add subject,Body,your mail Id,and receiver mail Id.
            sender.sendMail("Verification Code","Your verification code is: "+userCode,user,useremail);
            Log.d("send","done");
        }
        catch (Exception ex) {
            Log.d("exceptionsending",ex.toString());
        }
        return null;
    }

    @Override

    protected void onPostExecute(Void result) {

        super.onPostExecute(result);
        pDialog.cancel();

        Toast.makeText(AccountRegisterVerification.this,"New Verification Code Sent",Toast.LENGTH_SHORT).show();

    }
}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

@Override
protected void onStop() {
    super.onStop();
}

@Override
protected void onStart() {
    super.onStart();
}

@Override
protected void onResume() {
    handler.postDelayed(runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable,100);
            isNetworkAvailable();
            if (isNetworkAvailable()) {
                NoInternetCL.setVisibility(View.INVISIBLE);
            }
            else{
                NoInternetCL.setVisibility(View.VISIBLE);
            }
        }
    },100);
    super.onResume();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。