简体   繁体   中英

Sending Email Using apache commons mail package from android

I am new to android. I am developing the new app with email sending option. To send a mail I have used gmail configurations host "smtp.gmail.com", port 465 with SSL true. To send an email I have apache commons API. OnTouch event mail sending method will call. Whenever touch button it shows following errors,

Error : Could not find class 'javax.naming.InitialContext', referenced from method org.apache.commons.mail.Email.setMailSessionFromJNDI
    Warning: VFY: unable to resolve new-instance 955 (Ljavax/naming/InitialContext;) in Lorg/apache/commons/mail/Email;
    Warning : org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465

I have added uses-permission android:name="android.permission.INTERNET" in my manifest file.

Can i use all java files in android ?

My email code executed correctly as a stand alone java program.

Here is an example of what I am doing in an app. I have an app that has its own email account that sends an email to the user when they fill out a form and press the submit button.

Important make sure you have the libSMTP.jar file referenced in your app. I am using this library for the following code. Here is the following code being used, take from it what you'd like, hope this is useful:

Imports needed:

import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;

Submit button to make the request to send email

 submit.setOnClickListener(new OnClickListener()
    {       
        public void onClick(View v)
        {
            //-- Submit saves data to sqlite db, but removed that portion for this demo...


            //-- Executes an new task to send an automated email to user when they fill out a form...
            new sendEmailTask().execute();
        }
        }
    });

Email task to be preformed on seperate thread:

private class sendEmailTask extends AsyncTask<Void, Void, Void>
{

    @Override
    protected void onPostExecute(Void result) 
    {

    }

    @Override
    protected void onPreExecute() 
    {

    }

    @SuppressLint("ParserError")
    @Override
    protected Void doInBackground(Void... params) 
    {

        try {

            //--Note the send format is as follows: send(from, to, subject line, body message)
            send("myAppName@gmail.com",  "emailToSendTo@gmail.com", "Form Submitted",  "You submitted the form.");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Send function being used:

public void send(String from, String to, String subject, String text) throws IOException 
{
    SMTPClient client = new SMTPClient("UTF-8");
    client.setDefaultTimeout(60 * 1000);

    client.setRequireStartTLS(true); // requires STARTTLS
    //client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
    client.setUseAuth(true); // use SMTP AUTH
    //client.setAuthMechanisms(authMechanisms); // sets AUTH mechanisms e.g. LOGIN

    client.connect("smtp.gmail.com", 587);
    checkReply(client);

    //--Note the following format is as follows: client.login("localhost", (...your email account being used to send email from...), (...your email accounts password ...));
    client.login("localhost", "myAppName@gmail.com", "...myAppName email account password...");
    checkReply(client);

    client.setSender(from);
    checkReply(client);
    client.addRecipient(to);
    checkReply(client);

    Writer writer = client.sendMessageData();

    if (writer != null) 
    {
        SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
        writer.write(header.toString());
        writer.write(text);
        writer.close();
        client.completePendingCommand();
            checkReply(client);
    }

    client.logout();
    client.disconnect();
}

Check reply function being used:

private void checkReply(SMTPClient sc) throws IOException 
{
    if (SMTPReply.isNegativeTransient(sc.getReplyCode())) 
    {
        sc.disconnect();
        throw new IOException("Transient SMTP error " + sc.getReplyCode());
    } 
    else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) 
    {
        sc.disconnect();
        throw new IOException("Permanent SMTP error " + sc.getReplyCode());
    }
}

从Apache Commons Net 3.3中,您可以将jar放在类路径中,然后开始使用AuthenticationSMTPClient: http : //blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android -with-apache-commons-net /

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