繁体   English   中英

注册Android应用程序后发送验证电子邮件

[英]Send verification email after sign-up android app

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

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

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

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

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

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

    公共类 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); }

    }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM