简体   繁体   中英

Send email through App without opening mail App in Android

so I searched a lot to send an email throught my app, but without the user having to log in in an email app and send it himself. I would like to just let him write it in an editText and then just press a button and send it to me. So that's what I did: 2 classes for the mail thing, my activity which calls it, add the 3 libraries and the internet permission. What did I do wrong?

Here is where I call the email process :

private View.OnClickListener btnMode1Listener = new 
View.OnClickListener() {
    @Override
    public void onClick(View v) {
        suggestionText = entre_suggestion.getText().toString();

        Log.i("SendMailActivity", "Send Button Clicked.");

        String fromEmail = "fromEmail@gmail.com";
        String fromPassword = "frompassword";
        String toEmails = "toEmail@gmail.com";
        List toEmailList = Arrays.asList(toEmails
                .split("\\s*,\\s*"));
        Log.i("SendMailActivity", "To List: " + toEmailList);
        String emailSubject = "Suggestion";
        String emailBody = suggestionText;
        new SendMailTask(suggestions.this).execute(fromEmail,
                fromPassword, toEmailList, emailSubject, emailBody);

    }
};

This is the first class "GMail":

public class GMail {

final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";

String fromEmail;
String fromPassword;
List toEmailList;
String emailSubject;
String emailBody;

Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;

public GMail() {

}

public GMail(String fromEmail, String fromPassword,
             List toEmailList, String emailSubject, String emailBody) {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmailList = toEmailList;
    this.emailSubject = emailSubject;
    this.emailBody = emailBody;

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", smtpAuth);
    emailProperties.put("mail.smtp.starttls.enable", starttls);
    Log.i("GMail", "Mail server properties set.");
}

public MimeMessage createEmailMessage() throws AddressException,
        MessagingException, UnsupportedEncodingException {

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (Object toEmail : toEmailList) {
        Log.i("GMail","toEmail: "+toEmail);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress((String) toEmail));
    }

    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");// for a html email
    // emailMessage.setText(emailBody);// for a text email
    Log.i("GMail", "Email Message created.");
    return emailMessage;
}

public void sendEmail() throws AddressException, MessagingException {

    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromEmail, fromPassword);
    Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients());
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    Log.i("GMail", "Email sent successfully.");
}

}

And this is the second class "SendMailtask":

public class SendMailTask extends AsyncTask {

private ProgressDialog statusDialog;
private Activity sendMailActivity;

public SendMailTask(Activity activity) {
    sendMailActivity = activity;

}

protected void onPreExecute() {
    statusDialog = new ProgressDialog(sendMailActivity);
    statusDialog.setMessage("Getting ready...");
    statusDialog.setIndeterminate(false);
    statusDialog.setCancelable(false);
    statusDialog.show();
}

@Override
protected Object doInBackground(Object... args) {
    try {
        Log.i("SendMailTask", "About to instantiate GMail...");
        publishProgress("Processing input....");
        GMail androidEmail = new GMail(args[0].toString(),
                args[1].toString(), (List) args[2], args[3].toString(),
                args[4].toString());
        publishProgress("Preparing mail message....");
        androidEmail.createEmailMessage();
        publishProgress("Sending email....");
        androidEmail.sendEmail();
        publishProgress("Email Sent.");
        Log.i("SendMailTask", "Mail Sent.");
    } catch (Exception e) {
        publishProgress(e.getMessage());
        Log.e("SendMailTask", e.getMessage(), e);
    }
    return null;
}

@Override
public void onProgressUpdate(Object... values) {
    statusDialog.setMessage(values[0].toString());

}

@Override
public void onPostExecute(Object result) {
    statusDialog.dismiss();
}

}

And finally, the 3 librairies I added:

compile files('libs/activation.jar')
compile files('libs/additionnal.jar')
compile files('libs/mail.jar')

So yeah, I searched a lot and didn't find how to debug it. I tried a lot of different ways but it never sent the email. I just want to be clear that I don't want to open the mail app, I want the email to be sent without the user having to do something.

package com.auto.smartautomates.smartautomates.Helpers;

import com.crashlytics.android.Crashlytics;

import java.util.Calendar;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

/**
 * Created by sardar.khan on 6/8/2017.
 */

public class MailService {
    // public static final String MAIL_SERVER = "localhost";

    private String toList;
    private String ccList;
    private String bccList;
    private String subject;
    final private static String SMTP_SERVER = "smtp.gmail.com";
    private String from;
    private String txtBody;
    private String htmlBody;
    private String replyToList;
    private boolean authenticationRequired = false;

    public MailService(String from, String toList, String subject, String txtBody, String htmlBody) {
        this.txtBody = txtBody;
        this.htmlBody = htmlBody;
        this.subject = subject;
        this.from = from;
        this.toList = toList;
        this.ccList = null;
        this.bccList = null;
        this.replyToList = null;
        this.authenticationRequired = true;


    }


    public void sendAuthenticated() throws AddressException, MessagingException {
        authenticationRequired = true;
        send();
    }

    /**
     * Send an e-mail
     *
     * @throws MessagingException
     * @throws AddressException
     */
    public void send() throws AddressException, MessagingException {
        Properties props = new Properties();

        // set the host smtp address
        props.put("mail.smtp.host", SMTP_SERVER);
        props.put("mail.user", from);

        props.put("mail.smtp.starttls.enable", "true");  // needed for gmail
        props.put("mail.smtp.auth", "true"); // needed for gmail
        props.put("mail.smtp.port", "587");  // gmail smtp port 587 default gmail

        /*Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("mobile@mydomain.com", "mypassword");
            }
        };*/


        Session session;

        if (authenticationRequired) {
            Authenticator auth = new SMTPAuthenticator();
            props.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(props, auth);
        } else {
            session = Session.getDefaultInstance(props, null);
        }

        // get the default session
        session.setDebug(true);

        // create message
        Message msg = new javax.mail.internet.MimeMessage(session);

        // set from and to address
        try {
            msg.setFrom(new InternetAddress(from, from));
            msg.setReplyTo(new InternetAddress[]{new InternetAddress(from,from)});
        } catch (Exception e) {
            Crashlytics.logException(e);
            msg.setFrom(new InternetAddress(from));
            msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
        }

        // set send date
        msg.setSentDate(Calendar.getInstance().getTime());

        // parse the recipients TO address
        java.util.StringTokenizer st = new java.util.StringTokenizer(toList, ",");
        int numberOfRecipients = st.countTokens();

        javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[numberOfRecipients];

        int i = 0;
        while (st.hasMoreTokens()) {
            addressTo[i++] = new javax.mail.internet.InternetAddress(st
                    .nextToken());
        }
        msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);

        // parse the replyTo addresses
        if (replyToList != null && !"".equals(replyToList)) {
            st = new java.util.StringTokenizer(replyToList, ",");
            int numberOfReplyTos = st.countTokens();
            javax.mail.internet.InternetAddress[] addressReplyTo = new javax.mail.internet.InternetAddress[numberOfReplyTos];
            i = 0;
            while (st.hasMoreTokens()) {
                addressReplyTo[i++] = new javax.mail.internet.InternetAddress(
                        st.nextToken());
            }
            msg.setReplyTo(addressReplyTo);
        }

        // parse the recipients CC address
        if (ccList != null && !"".equals(ccList)) {
            st = new java.util.StringTokenizer(ccList, ",");
            int numberOfCCRecipients = st.countTokens();

            javax.mail.internet.InternetAddress[] addressCC = new javax.mail.internet.InternetAddress[numberOfCCRecipients];

            i = 0;
            while (st.hasMoreTokens()) {
                addressCC[i++] = new javax.mail.internet.InternetAddress(st
                        .nextToken());
            }

            msg.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
        }

        // parse the recipients BCC address
        if (bccList != null && !"".equals(bccList)) {
            st = new java.util.StringTokenizer(bccList, ",");
            int numberOfBCCRecipients = st.countTokens();

            javax.mail.internet.InternetAddress[] addressBCC = new javax.mail.internet.InternetAddress[numberOfBCCRecipients];

            i = 0;
            while (st.hasMoreTokens()) {
                addressBCC[i++] = new javax.mail.internet.InternetAddress(st
                        .nextToken());
            }

            msg.setRecipients(javax.mail.Message.RecipientType.BCC, addressBCC);
        }

        // set header
        msg.addHeader("X-Mailer", "MyAppMailer");
        msg.addHeader("Precedence", "bulk");
        // setting the subject and content type
        msg.setSubject(subject);

        Multipart mp = new MimeMultipart("related");

        // set body message
        MimeBodyPart bodyMsg = new MimeBodyPart();
        bodyMsg.setText(txtBody, "iso-8859-1");
        bodyMsg.setContent(htmlBody, "text/html");
        mp.addBodyPart(bodyMsg);
        msg.setContent(mp);

        // send it
        try {
            javax.mail.Transport.send(msg);
        } catch (Exception e) {
            Crashlytics.logException(e);
            e.printStackTrace();
        }

    }

    /**
     * SimpleAuthenticator is used to do simple authentication when the SMTP
     * server requires it.
     */
    private static class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            String username = "someEmail@gmail.com";
            String password ="yourPassword";

            return new PasswordAuthentication(username, password);
        }
    }

    public String getToList() {
        return toList;
    }

    public void setToList(String toList) {
        this.toList = toList;
    }

    public String getCcList() {
        return ccList;
    }

    public void setCcList(String ccList) {
        this.ccList = ccList;
    }

    public String getBccList() {
        return bccList;
    }

    public void setBccList(String bccList) {
        this.bccList = bccList;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public void setTxtBody(String body) {
        this.txtBody = body;
    }

    public void setHtmlBody(String body) {
        this.htmlBody = body;
    }

    public String getReplyToList() {
        return replyToList;
    }

    public void setReplyToList(String replyToList) {
        this.replyToList = replyToList;
    }

    public boolean isAuthenticationRequired() {
        return authenticationRequired;
    }

    public void setAuthenticationRequired(boolean authenticationRequired) {
        this.authenticationRequired = authenticationRequired;
    }

}

在您的帐户设置中,允许smtp和不安全的应用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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