使用现有的Gmail帐户并发送邮件

时间:2012-12-19 11:33:14

标签: android

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

这是我的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;
}
}

这是我的MailSenderActivity.java类

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();

    }
}

}

如果我手动设置GMAIL_EMAIL_ID,GMAIL_ACCOUNT_PASSWORD和TO_ADDRESSES,我就可以发送消息了。但是我已经在手机应用程序中获得了默认的GMAIL_EMAIL_ID和GMAIL_ACCOUNT_PASSWORD通道。

1 个答案:

答案 0 :(得分:0)

您可以使用此功能发送带附件的电子邮件:

public static void sendEmail(Context context, String emailTo, String emailCC, String subject, String emailText, String type, List<String> filePaths) {
    //need to "send multiple" to get more than one attachment
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType("image/png");
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{emailTo});
    emailIntent.putExtra(android.content.Intent.EXTRA_CC, new String[]{emailCC});
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailText);
    //has to be an ArrayList
    ArrayList<Uri> uris = new ArrayList<Uri>();
    //convert from paths to Android friendly Parcelable Uri's
    if(filePaths != null) {
        for (String file : filePaths) {
            File fileIn = new File(file);
            Uri u = Uri.fromFile(fileIn);
            uris.add(u);
        }
        emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    }
    try {
        context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_email_using_message)));
    }catch (ActivityNotFoundException e) {
        new DigitalReplicaDialog(context, context.getResources().getString(R.string.email_not_configured_warning)).show();
    }
}