Android 使用现有的gmail帐户发送邮件

Android 使用现有的gmail帐户发送邮件,android,Android,到目前为止,我已经通过各种论坛,发现我们必须得到令牌发送电子邮件。我尝试过各种方式,但无法向任何人发送邮件。任何人都可以通过发送与此相关的各种链接来帮助我 这是我的Mail.java类 package com.mycomp.android.test; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activat

到目前为止,我已经通过各种论坛,发现我们必须得到令牌发送电子邮件。我尝试过各种方式,但无法向任何人发送邮件。任何人都可以通过发送与此相关的各种链接来帮助我

这是我的Mail.java类

package com.mycomp.android.test;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
 import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {

private Multipart attachements;


private String fromAddress = "";
private String accountEmail = "";
private String accountPassword = "";
private String smtpHost = "smtp.gmail.com";
private String smtpPort = "465"; // 465,587
private String toAddresses = "";
private String mailSubject = "";
private String mailBody = "";


public Mail() {
    attachements = new MimeMultipart();


}

public Mail(String user, String pass) {
    this();
    accountEmail = user;
    accountPassword = pass;
}

public boolean send() throws Exception {

    Properties props = new Properties();
    //props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", smtpPort);
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    try {
        Session session = Session.getInstance(props, this);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        //fill message
        messageBodyPart.setText(mailBody);
        // add to multipart
        attachements.addBodyPart(messageBodyPart);

        //msg.setText(mailBody);
        msg.setSubject(mailSubject);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.addRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddresses));
        msg.setContent(attachements);

        Transport transport = session.getTransport("smtps");
        transport.connect(smtpHost, 465, accountEmail, accountPassword);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

public void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
//      messageBodyPart.setFileName("filename");
    attachements.addBodyPart(messageBodyPart);
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(accountEmail, accountPassword);
}

/**
 * Gets the fromAddress.
 * 
 * @return <tt> the fromAddress.</tt>
 */
public String getFromAddress() {
    return fromAddress;
}

/**
 * Sets the fromAddress.
 *
 * @param fromAddress <tt> the fromAddress to set.</tt>
 */
public void setFromAddress(String fromAddress) {
    this.fromAddress = fromAddress;
}

/**
 * Gets the toAddresses.
 * 
 * @return <tt> the toAddresses.</tt>
 */
public String getToAddresses() {
    return toAddresses;
}

/**
 * Sets the toAddresses.
 *
 * @param toAddresses <tt> the toAddresses to set.</tt>
 */
public void setToAddresses(String toAddresses) {
    this.toAddresses = toAddresses;
}

/**
 * Gets the mailSubject.
 * 
 * @return <tt> the mailSubject.</tt>
 */
public String getMailSubject() {
    return mailSubject;
}

/**
 * Sets the mailSubject.
 *
 * @param mailSubject <tt> the mailSubject to set.</tt>
 */
public void setMailSubject(String mailSubject) {
    this.mailSubject = mailSubject;
}

/**
 * Gets the mailBody.
 * 
 * @return <tt> the mailBody.</tt>
 */
public String getMailBody() {
    return mailBody;
}

/**
 * Sets the mailBody.
 *
 * @param mailBody <tt> the mailBody to set.</tt>
 */
public void setMailBody(String mailBody) {
    this.mailBody = mailBody;
}
}
package com.mycomp.android.test;

        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.util.regex.Pattern;

        import android.accounts.Account;
        import android.accounts.AccountManager;
        import android.app.Activity;
        import android.app.ProgressDialog;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.os.StrictMode;
        import android.util.Log;
        import android.util.Patterns;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

 public class MailSenderActivity extends Activity {
AccountManager am = AccountManager.get(this); // "this" references the current Context
 Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = am.getAccountsByType("com.google");


private static final String GMAIL_EMAIL_ID = "From Email Address";
private static final String GMAIL_ACCOUNT_PASSWORD = "password";
private static final String TO_ADDRESSES = "To Email Address";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    writeFile();

    final Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            new MailSenderActivity.MailSender().execute();
        }
    });

}

private File imageFile;

private boolean writeFile() {
    imageFile = new File(
            getApplicationContext().getFilesDir() + "/images/",
            "sample.png");

    String savePath = imageFile.getAbsolutePath();
    System.out.println("savePath :" + savePath + ":");

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(savePath, false);
    } catch (FileNotFoundException ex) {
        String parentName = new File(savePath).getParent();
        if (parentName != null) {
            File parentDir = new File(parentName);
            if ((!(parentDir.exists())) && (parentDir.mkdirs()))
                try {
                    fileOutputStream = new FileOutputStream(savePath, false);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

        }
    }

    // here i am using a png from drawable resources as attachment. You can use your own image byteArray while sending mail. 
    Bitmap bitmap = BitmapFactory.decodeResource(
            MailSenderActivity.this.getResources(), R.drawable.english);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] imgBuffer = stream.toByteArray();

    boolean result = true;

    try {
        fileOutputStream.write(imgBuffer);
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        result = false;
    } catch (IOException e2) {
        e2.printStackTrace();
        result = false;
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                result = false;
            }
        }
    }

    return result;

}

class MailSender extends AsyncTask<Void, Integer, Integer> {

    ProgressDialog pd = null;

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pd = new ProgressDialog(MailSenderActivity.this);
        pd.setTitle("Uploading...");
        pd.setMessage("Uploading image. Please wait...");
        pd.setCancelable(false);
        pd.show();

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Integer doInBackground(Void... params) {


        Mail m = new Mail(GMAIL_EMAIL_ID, GMAIL_ACCOUNT_PASSWORD);

        String toAddresses = TO_ADDRESSES;
        m.setToAddresses(toAddresses);
        m.setFromAddress(GMAIL_EMAIL_ID);
        m.setMailSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
        m.setMailBody("Email body.");

//          try {
//              ZipUtility.zipDirectory(new File("/mnt/sdcard/images"),
//                      new File("/mnt/sdcard/logs.zip"));
//          } catch (IOException e1) {
//              Log.e("MailApp", "Could not zip folder", e1);
//          }

        try {
            String path = imageFile.getAbsolutePath();
            System.out.println("sending path:" + path + ":");
            m.addAttachment(path);

            // m.addAttachment("/mnt/sdcard/logs.zip");

            if (m.send()) {
                System.out.println("Message sent");
                return 1;
            } else {
                return 2;
            }

        } catch (Exception e) {
            Log.e("MailApp", "Could not send email", e);
        }
        return 3;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Integer result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        pd.dismiss();

        if (result == 1)
            Toast.makeText(MailSenderActivity.this,
                    "Email was sent successfully.", Toast.LENGTH_LONG)
                    .show();
        else if (result == 2)
            Toast.makeText(MailSenderActivity.this, "Email was not sent.",
                    Toast.LENGTH_LONG).show();
        else if (result == 3)
            Toast.makeText(MailSenderActivity.this,
                    "There was a problem sending the email.",
                    Toast.LENGTH_LONG).show();

    }
}

}
package com.mycop.android.test;
导入java.util.Properties;
导入javax.activation.DataHandler;
导入javax.activation.DataSource;
导入javax.activation.FileDataSource;
导入javax.mail.BodyPart;
导入javax.mail.Message;
导入javax.mail.Multipart;
导入javax.mail.PasswordAuthentication;
导入javax.mail.Session;
导入javax.mail.Transport;
导入javax.mail.internet.InternetAddress;
导入javax.mail.internet.MimeBodyPart;
导入javax.mail.internet.mimessage;
导入javax.mail.internet.MimeMultipart;
公共类邮件扩展了javax.Mail.Authenticator{
私人多部分附件;
私有字符串fromAddress=“”;
私人字符串accountEmail=“”;
私有字符串accountPassword=“”;
私有字符串smtpHost=“smtp.gmail.com”;
私有字符串smtpPort=“465”//465587
私有字符串toaddress=“”;
私有字符串mailSubject=“”;
私有字符串mailBody=“”;
公共邮件(){
attachements=新的MimeMultipart();
}
公共邮件(字符串用户、字符串传递){
这个();
accountEmail=用户;
accountPassword=通过;
}
public boolean send()引发异常{
Properties props=新属性();
//props.put(“mail.smtp.user”,d_email);
props.put(“mail.smtp.host”,smtpHost);
props.put(“mail.smtp.port”,smtpPort);
props.put(“mail.smtp.starttls.enable”、“true”);
props.put(“mail.smtp.debug”,“true”);
props.put(“mail.smtp.auth”,“true”);
props.put(“mail.smtp.socketFactory.port”,smtpPort);
props.put(“mail.smtp.socketFactory.class”,
“javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.socketFactory.fallback”、“false”);
试一试{
Session Session=Session.getInstance(props,this);
session.setDebug(true);
MimeMessage msg=新MimeMessage(会话);
//创建消息部分
MimeBodyPart messageBodyPart=新的MimeBodyPart();
//填充消息
messageBodyPart.setText(邮件正文);
//添加到多部分
附件.addBodyPart(messageBodyPart);
//msg.setText(邮件正文);
msg.setSubject(邮件主题);
msg.setFrom(新的InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO,
解析(toaddress));
msg.setContent(附件);
传输=session.getTransport(“smtps”);
传输连接(smtpHost,465,accountEmail,accountPassword);
transport.sendMessage(msg,msg.getAllRecipients());
transport.close();
返回true;
}捕获(例外e){
返回false;
}
}
public void addAttachment(字符串文件名)引发异常{
BodyPart messageBodyPart=新的MimeBodyPart();
DataSource source=新文件DataSource(文件名);
setDataHandler(新的DataHandler(源));
//messageBodyPart.setFileName(“文件名”);
附件.addBodyPart(messageBodyPart);
}
@凌驾
公共密码身份验证getPasswordAuthentication(){
返回新密码验证(accountEmail、accountPassword);
}
/**
*获取发件人地址。
* 
*@返回发件人地址。
*/
公共字符串getFromAddress(){
从地址返回;
}
/**
*设置发件人地址。
*
*@param fromAddress要设置的fromAddress。
*/
公共void setFromAddress(字符串fromAddress){
this.fromAddress=fromAddress;
}
/**
*获取ToAddress。
* 
*@返回toaddress。
*/
公共字符串getToAddresses(){
返回地址;
}
/**
*设置ToAddress。
*
*@param toaddress用于设置toaddress。
*/
public void settoaddress(字符串toaddress){
this.toaddress=toaddress;
}
/**
*获取邮件主题。
* 
*@返回邮件主题。
*/
公共字符串getMailSubject(){
返回邮件主题;
}
/**
*设置邮件主题。
*
*@param mailSubject要设置的mailSubject。
*/
public void setMailSubject(字符串mailSubject){
this.mailSubject=mailSubject;
}
/**
*获取邮件正文。
* 
*@返回邮件正文。
*/
公共字符串getMailBody(){
返回邮件体;
}
/**
*设置邮件正文。
*
*@param mailBody要设置的mailBody。
*/
公共void setMailBody(字符串mailBody){
this.mailBody=mailBody;
}
}
这是我的MailSenderActivity.java类

package com.mycomp.android.test;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
 import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {

private Multipart attachements;


private String fromAddress = "";
private String accountEmail = "";
private String accountPassword = "";
private String smtpHost = "smtp.gmail.com";
private String smtpPort = "465"; // 465,587
private String toAddresses = "";
private String mailSubject = "";
private String mailBody = "";


public Mail() {
    attachements = new MimeMultipart();


}

public Mail(String user, String pass) {
    this();
    accountEmail = user;
    accountPassword = pass;
}

public boolean send() throws Exception {

    Properties props = new Properties();
    //props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", smtpPort);
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    try {
        Session session = Session.getInstance(props, this);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        //fill message
        messageBodyPart.setText(mailBody);
        // add to multipart
        attachements.addBodyPart(messageBodyPart);

        //msg.setText(mailBody);
        msg.setSubject(mailSubject);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.addRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddresses));
        msg.setContent(attachements);

        Transport transport = session.getTransport("smtps");
        transport.connect(smtpHost, 465, accountEmail, accountPassword);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

public void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
//      messageBodyPart.setFileName("filename");
    attachements.addBodyPart(messageBodyPart);
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(accountEmail, accountPassword);
}

/**
 * Gets the fromAddress.
 * 
 * @return <tt> the fromAddress.</tt>
 */
public String getFromAddress() {
    return fromAddress;
}

/**
 * Sets the fromAddress.
 *
 * @param fromAddress <tt> the fromAddress to set.</tt>
 */
public void setFromAddress(String fromAddress) {
    this.fromAddress = fromAddress;
}

/**
 * Gets the toAddresses.
 * 
 * @return <tt> the toAddresses.</tt>
 */
public String getToAddresses() {
    return toAddresses;
}

/**
 * Sets the toAddresses.
 *
 * @param toAddresses <tt> the toAddresses to set.</tt>
 */
public void setToAddresses(String toAddresses) {
    this.toAddresses = toAddresses;
}

/**
 * Gets the mailSubject.
 * 
 * @return <tt> the mailSubject.</tt>
 */
public String getMailSubject() {
    return mailSubject;
}

/**
 * Sets the mailSubject.
 *
 * @param mailSubject <tt> the mailSubject to set.</tt>
 */
public void setMailSubject(String mailSubject) {
    this.mailSubject = mailSubject;
}

/**
 * Gets the mailBody.
 * 
 * @return <tt> the mailBody.</tt>
 */
public String getMailBody() {
    return mailBody;
}

/**
 * Sets the mailBody.
 *
 * @param mailBody <tt> the mailBody to set.</tt>
 */
public void setMailBody(String mailBody) {
    this.mailBody = mailBody;
}
}
package com.mycomp.android.test;

        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.util.regex.Pattern;

        import android.accounts.Account;
        import android.accounts.AccountManager;
        import android.app.Activity;
        import android.app.ProgressDialog;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.os.StrictMode;
        import android.util.Log;
        import android.util.Patterns;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

 public class MailSenderActivity extends Activity {
AccountManager am = AccountManager.get(this); // "this" references the current Context
 Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = am.getAccountsByType("com.google");


private static final String GMAIL_EMAIL_ID = "From Email Address";
private static final String GMAIL_ACCOUNT_PASSWORD = "password";
private static final String TO_ADDRESSES = "To Email Address";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    writeFile();

    final Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            new MailSenderActivity.MailSender().execute();
        }
    });

}

private File imageFile;

private boolean writeFile() {
    imageFile = new File(
            getApplicationContext().getFilesDir() + "/images/",
            "sample.png");

    String savePath = imageFile.getAbsolutePath();
    System.out.println("savePath :" + savePath + ":");

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(savePath, false);
    } catch (FileNotFoundException ex) {
        String parentName = new File(savePath).getParent();
        if (parentName != null) {
            File parentDir = new File(parentName);
            if ((!(parentDir.exists())) && (parentDir.mkdirs()))
                try {
                    fileOutputStream = new FileOutputStream(savePath, false);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

        }
    }

    // here i am using a png from drawable resources as attachment. You can use your own image byteArray while sending mail. 
    Bitmap bitmap = BitmapFactory.decodeResource(
            MailSenderActivity.this.getResources(), R.drawable.english);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] imgBuffer = stream.toByteArray();

    boolean result = true;

    try {
        fileOutputStream.write(imgBuffer);
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        result = false;
    } catch (IOException e2) {
        e2.printStackTrace();
        result = false;
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                result = false;
            }
        }
    }

    return result;

}

class MailSender extends AsyncTask<Void, Integer, Integer> {

    ProgressDialog pd = null;

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pd = new ProgressDialog(MailSenderActivity.this);
        pd.setTitle("Uploading...");
        pd.setMessage("Uploading image. Please wait...");
        pd.setCancelable(false);
        pd.show();

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Integer doInBackground(Void... params) {


        Mail m = new Mail(GMAIL_EMAIL_ID, GMAIL_ACCOUNT_PASSWORD);

        String toAddresses = TO_ADDRESSES;
        m.setToAddresses(toAddresses);
        m.setFromAddress(GMAIL_EMAIL_ID);
        m.setMailSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
        m.setMailBody("Email body.");

//          try {
//              ZipUtility.zipDirectory(new File("/mnt/sdcard/images"),
//                      new File("/mnt/sdcard/logs.zip"));
//          } catch (IOException e1) {
//              Log.e("MailApp", "Could not zip folder", e1);
//          }

        try {
            String path = imageFile.getAbsolutePath();
            System.out.println("sending path:" + path + ":");
            m.addAttachment(path);

            // m.addAttachment("/mnt/sdcard/logs.zip");

            if (m.send()) {
                System.out.println("Message sent");
                return 1;
            } else {
                return 2;
            }

        } catch (Exception e) {
            Log.e("MailApp", "Could not send email", e);
        }
        return 3;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Integer result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        pd.dismiss();

        if (result == 1)
            Toast.makeText(MailSenderActivity.this,
                    "Email was sent successfully.", Toast.LENGTH_LONG)
                    .show();
        else if (result == 2)
            Toast.makeText(MailSenderActivity.this, "Email was not sent.",
                    Toast.LENGTH_LONG).show();
        else if (result == 3)
            Toast.makeText(MailSenderActivity.this,
                    "There was a problem sending the email.",
                    Toast.LENGTH_LONG).show();

    }
}

}
package com.mycop.android.test;
导入java.io.ByteArrayOutputStream;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.util.regex.Pattern;
导入android.accounts.Account;
导入android.accounts.AccountManager;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.util.Log;
导入android.util.Patterns;
导入android.view.view;
导入android.widget.Button;
导入android.widget.Toast;
公共类MailSenderActivity扩展活动{
AccountManager am=AccountManager.get(this);/“this”引用当前上下文
Pattern emailPattern=Patterns.EMAIL\u地址;
Account[]accounts=am.getAccountsByType(“com.google”);
私有静态最终字符串GMAIL\u EMAIL\u ID=“来自电子邮件地址”;
私有静态最终字符串GMAIL\u ACCOUNT\u PASSWORD=“PASSWORD”;
私有静态最终字符串至_ADDRESSES=“至电子邮件地址”;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
设置