简体   繁体   English

从Android应用程序发送电子邮件

[英]Sending email from android application

When the user hits the sign up button, I want a verification email to be sent to the user. 当用户点击“注册”按钮时,我希望将验证电子邮件发送给该用户。 But there is something wrong out here. 但是这里出了点问题。 The email is not sent and even if pass the wrong email address and password in GmailSender, the code throws no error at all. 电子邮件不会发送,即使在GmailSender中输入了错误的电子邮件地址和密码,代码也不会抛出任何错误。

This is code block for the sign up page. 这是注册页面的代码块。

package com.example.grocerycodeu.grocerycloud.ui;

    import android.app.Fragment;
    import android.app.LoaderManager;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.Loader;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.provider.ContactsContract;
    import android.telephony.TelephonyManager;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.EditText;
    import android.widget.Toast;

    import com.example.grocerycodeu.grocerycloud.GMailSender;
    import com.example.grocerycodeu.grocerycloud.R;
    import com.example.grocerycodeu.grocerycloud.UserLoginActivity;
    import com.example.grocerycodeu.grocerycloud.database.EntryDatabase;
    import com.example.grocerycodeu.grocerycloud.database.GroceryContract;
    import com.example.grocerycodeu.grocerycloud.sync.request.GroceryRequest;
    import com.example.grocerycodeu.grocerycloud.sync.request.HttpRequest;

    import java.io.IOException;
    import java.net.HttpURLConnection;

    public class UserSignUpFragment extends Fragment implements LoaderManager.LoaderCallbacks<HttpURLConnection> {

        public final static String EXTRA_MESSAGE = "com.example.grocerycodeu.grocerycloud.ui";

        EditText txtUsername;
        EditText txtPassword;
        EditText txtPasswordRetype;
        EditText txtEmail;
        CheckBox findMe;
        Button btnSignUp;

        String username;
        String password;
        String repassword;
        String email;
        String popupmsg;
        boolean checkedMyNumber;
        boolean checkedShareContact;

        //Get a reference to this fragment
        final UserSignUpFragment thisFragment = this;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            popupmsg = "";
            checkedMyNumber = checkedShareContact = false;

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            //Get the root view
            View rootView = inflater.inflate(R.layout.fragment_signup, container, false);

            //Find the edit text views
            txtUsername = (EditText) rootView.findViewById(R.id.username_text_view);
            txtPassword = (EditText) rootView.findViewById(R.id.password_text_view);
            txtPasswordRetype = (EditText) rootView.findViewById(R.id.password_retype_text_view);
            txtEmail = (EditText) rootView.findViewById(R.id.email_text_view);

            // Allow user to his/her  phone number
            findMe = (CheckBox) rootView.findViewById(R.id.checkbox_sharing);
            findMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                                  @Override
                                                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                                      checkedMyNumber = !checkedMyNumber;
                                                      if (checkedMyNumber) {
                                                          Log.e("STATUS", "" + checkedMyNumber);
                                                          readMyNumber();
                                                      }
                                                  }
                                              }
            );

            // Allow user to share contact list
            findMe = (CheckBox) rootView.findViewById(R.id.checkbox_sharing_contacts);
            findMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                                  @Override
                                                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                                      checkedShareContact = !checkedShareContact;
                                                      Log.e("STATUS", "" + checkedShareContact);
                                                  }
                                              }
            );


            //Find the login button
            btnSignUp = (Button) rootView.findViewById(R.id.sign_up_button);

            //Go to the sign up activity
            btnSignUp.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    //Get the user data
                    username = txtUsername.getText().toString();
                    password = txtPassword.getText().toString();
                    repassword = txtPasswordRetype.getText().toString();
                    email = txtEmail.getText().toString();

                    //validate user input
                    if (validateAllUserInput()) {

                        // create a new user
                        Bundle args = new Bundle();
                        if (checkedShareContact) {
                            readContacts();
                            getLoaderManager().initLoader(GroceryRequest.OPCODE_LIST_CREATE, args, thisFragment).forceLoad();
                        } else {
                            getLoaderManager().initLoader(GroceryRequest.OPCODE_LIST_CREATE, args, thisFragment).forceLoad();
                        }
                    } else {
                        Toast toast = Toast.makeText(getActivity(),
                                popupmsg, Toast.LENGTH_SHORT);
                        toast.show();
                        popupmsg = "";
                    }
                }
            });

            return rootView;
        }

        @Override
        public Loader<HttpURLConnection> onCreateLoader(int id, Bundle args) {

            return GroceryRequest.userCreate(getActivity(),
                    username,
                    password);
        }

        @Override
        public void onLoadFinished(Loader<HttpURLConnection> loader, HttpURLConnection data) {

            try {
                //Check if the response code is a success
                int id = data.getResponseCode();
                if (id >= 200 && id < 300) {

                    //Get the user key from the request
                    String userKey = HttpRequest.getContentString(data);

                    Log.d("Hello", "1");
                    //Check if the user exists in the database

                    EntryDatabase<GroceryContract.UserEntry> entryDatabase = GroceryContract.UserEntry.getDatabase();

                    GroceryContract.UserEntry users[] = entryDatabase.query(getActivity(),
                            GroceryContract.UserEntry.COLUMN_USER_KEY + " = ?",
                            new String[]{userKey}, null);

                    Log.d("Hello", "2ss");
                    //Add the user to the database
                    if (users.length == 0) {
                        Log.d("Hello", "3");

                        //Set the values of the user
                        GroceryContract.UserEntry user = new GroceryContract.UserEntry(userKey, username, null);
                        entryDatabase.put(getActivity(), user);
                        Log.d("NewUser", user.userKey);
                    }


                    //Go to the login page after usr is created
                    Intent intent = new Intent(thisFragment.getActivity(), UserLoginActivity.class);
                    String[] user_info = {username, password};
                    intent.putExtra(EXTRA_MESSAGE, user_info);
                    startActivity(intent);
                } else {
                    Toast toast = Toast.makeText(getActivity(),
                            "User with the given user name already exists.", Toast.LENGTH_SHORT);
                    toast.show();
                }
            } catch (IOException e) {
                Log.d("Login", e.toString());
            }

            //Clean up so the request can be made again
            getLoaderManager().destroyLoader(GroceryRequest.OPCODE_USER_CREATE);
        }

        @Override
        public void onLoaderReset(Loader<HttpURLConnection> loader) {
        }

        public boolean validateAllUserInput() {
            boolean isusernamevaild = validateUserName();
            boolean ispasswordvalid = validatePassword();
            boolean isemailvalid = validateEmail();
            if (isemailvalid && ispasswordvalid && isusernamevaild) {
                return true;
            } else {
                return false;
            }
        }

        public boolean validateUserName() {
            if (username.length() <= 0) {
                popupmsg += "Please enter a user name.\n";
            } else if (username.length() > 15 || username.length() < 3) {
                popupmsg += "User name must be between 3 to 15 characters.\n";
                txtUsername.setText(null);
            } else {
                return true;
            }
            return false;
        }

        public boolean validatePassword() {
            if (password.equals(repassword) && password.length() >= 5) {
                return true;
            } else if (password.length() == 0) {
                popupmsg += "Please enter a password.\n";

            } else if (password.length() < 5) {
                popupmsg += "Please enter a password that is 5 character long.\n";

            } else {
                popupmsg += "Please enter the password again, password mis-match.\n";
            }
            txtPassword.setText(null);
            txtPasswordRetype.setText(null);
            return false;
        }

        public boolean validateEmail() {

            String Expn =
                    "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                            + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                            + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                            + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                            + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                            + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

            if (email.length() == 0) {
                popupmsg += "Please enter an email address.\n";
                return false;
            } else if (email.matches(Expn) && email.length() > 0) {
                try {
                    GMailSender sender = new GMailSender("senderemail@gmail.com", "**********");
                    sender.sendMail("This is Subject",
                            "This is Body",
                            "senderemail@gmail.com",
                            "receiver@gmail.com");
                    Log.e("Check point", "Get inside the gmail sender");
                    return true;
                } catch (Exception e) {
                    Log.e("SendMail", e.getMessage(), e);
                    return false;
                }
            } else {
                popupmsg += "Please re-enter a valid email address.\n";
                txtEmail.setText(null);
                return false;
            }
        }

        public void readMyNumber() {
            TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
            String number = tm.getLine1Number();
            // I guess a code block must be added to add phoen number to db
            Log.e("My Number", number + "");
        }

        public void readContacts() {
            ContentResolver cr = getActivity().getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, null);
            Log.e("Length", "" + cur.getCount());
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        System.out.println("name : " + name + ", ID : " + id);

                        // get the phone number
                        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{id}, null);
                        while (pCur.moveToNext()) {
                            String phone = pCur.getString(
                                    pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            // I guess a code block must be added to add phoen number to db

                            Log.e("phone", " " + phone);
                        }
                        pCur.close();
                    }
                }
            }
        }

    }

This is the GmailSender class. 这是GmailSender类。

package com.example.grocerycodeu.grocerycloud;

import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

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;

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 com.example.grocerycodeu.grocerycloud.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);
            Log.e("SEND EMAIL", "IN SEND EMAIL - NO ERROR");
            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.e("FOUND AN ERROR", "IN SEND EMAIL_ GMAIL");
        }
    }

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

There seems no major issues with your code implementation except for the following line props.setProperty("mail.host", mailhost); 除了以下代码行props.setProperty("mail.host", mailhost);您的代码实现似乎没有重大问题props.setProperty("mail.host", mailhost); , try changing this to props.setProperty("mail.smtp.host", mailhost); ,请尝试将其更改为props.setProperty("mail.smtp.host", mailhost);

If you still have issues, then you may implement changes to your code based on the slightly different sample given by Bill the Lizard here https://stackoverflow.com/a/47452/3747037 . 如果仍有问题,则可以根据蜥蜴人Bill在此处提供的示例稍有不同,对代码进行更改, 网址为https://stackoverflow.com/a/47452/3747037

Hope this helps. 希望这可以帮助。

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

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