gpt4 book ai didi

java - 注册安卓应用后发送验证邮件

转载 作者:行者123 更新时间:2023-11-30 10:53:52 26 4
gpt4 key购买 nike

我正在使用 Android Studio 在 Debian Jessie 上构建一个 Android 应用程序。我希望能够实现一个电子邮件验证系统,当用户注册时,他们将自动收到一封包含链接的电子邮件。单击该链接会将数据库中的值从 false 更改为 true,以便对用户进行身份验证。

我听说我可以使用 JavaMail API 来完成这个?但同时听说我需要在本地主机上运行一个电子邮件服务器才能发送电子邮件?

我还没有找到明确的答案。任何帮助将不胜感激。谢谢。

最佳答案

可能我不知道对此的最佳答案。有两种方法可以做到这一点。

  1. 使用网络服务发送验证邮件。即假设您正在使用 PHP 网络服务来注册用户。当用户详细信息成功存储在数据库中时...您可以生成一个随机代码...将邮件发送到注册的电子邮件地址...在响应中获取该代码...并将其存储在首选项中以检查有效性.. 当用户输入时。

  2. 注册成功后....您可以通过触发某些对话框或任何其他方式向用户发送验证码...这是我的代码。我正在使用 volley 进行网络通话。

    公共(public)类 DialogRequestPassword 扩展了 Dialog 实现 android.view.View.OnClickListener {

    public Activity c;
    private PreferencesManager preferencesManager;
    DatabaseHelper db;
    private ProgressDialog progressDialog;
    EditText request_password;

    public DialogRequestPassword(Activity a) {
    super(a);
    this.c = a;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dialog_request_password);
    setCancelable(false);

    preferencesManager = new PreferencesManager(c);
    db = new DatabaseHelper(c);

    progressDialog = new ProgressDialog(c);
    progressDialog.setCancelable(false);
    progressDialog.setMessage("Getting Information...");

    TextView connectButton = (TextView) findViewById(R.id.connectButton);
    connectButton.setOnClickListener(this);

    request_password = (EditText) findViewById(R.id.request_password);

    TextView dialog_text = (TextView) findViewById(R.id.dialog_text);
    dialog_text.setText("Enter your registered email and request the lost password. You will receive steps to recover your password.");

    TextView cancelButton = (TextView) findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

    switch (v.getId()) {
    case R.id.cancelButton:
    dismiss();
    break;

    case R.id.connectButton:
    dismiss();
    // Send mail
    if (request_password.getText().toString().equals("")) {
    request_password.setError("Enter registered Email");
    } else {
    //Redirect user to Login
    if (preferencesManager.getVerificationCode() == null) {
    getUserData();
    }
    }
    break;

    }
    }


    /*******************************/
    private class SendMailTask extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    progressDialog.show();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    progressDialog.dismiss();
    }

    @Override
    protected Void doInBackground(String... receipt) {
    try {
    GMailSender sender = new GMailSender("ro-reply@gmail.com", "password");
    sender.sendMail("Password Recovery for App title",
    receipt[1],
    "user@gmail.com",
    receipt[0]);
    } catch (Exception e) {
    Log.d("SendMail", e.getMessage(), e);
    }
    return null;
    }
    }


    private void getUserData() {
    StringRequest jsonAuthenticate = new StringRequest(Request.Method.POST, Config.URL_REQUEST_PASSWORD,
    new Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
    if (Constants.DEBUG_MODE_ON)
    Log.d(Constants.DEBUG_LOG, "Response for Request Paswword: " + response);

    try {
    JSONObject result = new JSONObject(response);
    JSONArray jcode = result.getJSONArray("code");
    JSONObject jCodeObj = jcode.getJSONObject(0);
    int code = jCodeObj.getInt("code");

    if (code == 1) {


    } else {
    progressDialog.dismiss();
    Toast.makeText(c, "No such email is registered.", Toast.LENGTH_SHORT).show();
    }

    } catch (Exception e) {
    progressDialog.dismiss();

    Log.d(Constants.DEBUG_LOG, "Volley Exception: " + e.getCause() + " -> " + e.toString());

    e.printStackTrace();
    }
    }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    Toast.makeText(c, "Oh! Something went wrong. Please try again.", Toast.LENGTH_SHORT).show();
    progressDialog.dismiss();
    Log.d(Constants.DEBUG_LOG, "Error Response : " + error.toString() + " MESSAGE: " + error.getMessage() + " CAUSE:" + error.getCause());

    }
    }) {
    @Override
    protected Map<String, String> getParams() {
    Map<String, String> params = new HashMap<String, String>();

    params.put("email", request_password.getText().toString());
    return params;
    }
    };


    jsonAuthenticate.setRetryPolicy(new RetryPolicy() {
    @Override
    public int getCurrentTimeout() {
    return 10000;
    }

    @Override
    public int getCurrentRetryCount() {
    return 2;
    }

    @Override
    public void retry(VolleyError error) throws VolleyError {

    }
    });

    MyApplication.getInstance().addToReqQueue(jsonAuthenticate);
    }

注意:您必须为此使用 GmailLSender...

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

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;

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){

}
}

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

关于java - 注册安卓应用后发送验证邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33858608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com