使用代码在Gmail中附件

时间:2012-11-26 07:59:37

标签: android email attachment

我有使用gmail帐户发送电子邮件的工作代码,现在我只想使用代码进行附件而无需用户交互。

3 个答案:

答案 0 :(得分:1)

public synchronized void sendMail(String subject, String body, String sender, String recipients, File attachment) throws Exception {
    try{
    MimeMessage message = new MimeMessage(session);
    message.setSender(new InternetAddress(sender));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(body);

    MimeBodyPart mbp2 = new MimeBodyPart();
    FileDataSource fds = new FileDataSource(attachment);
    mbp2.setDataHandler(new DataHandler(fds));
    mbp2.setFileName(fds.getName());

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);

    message.setContent(mp);

    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){

    }
}

答案 1 :(得分:0)

如果您想从SDCard发送一些文件,请使用以下代码:

public static void email(Context context, String emailTo, String emailCC,
    String subject, String emailText, 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("text/plain");
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, 
        new String[]{emailTo});
    emailIntent.putExtra(android.content.Intent.EXTRA_CC, 
        new String[]{emailCC});
    //has to be an ArrayList
    ArrayList<Uri> uris = new ArrayList<Uri>();
    //convert from paths to Android friendly Parcelable Uri's
    for (String file : filePaths)
    {
        File fileIn = new File(file);
        Uri u = Uri.fromFile(fileIn);
        uris.add(u);
    }
    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}

Android Intent for sending email with attachment

Android multiple email attachments using Intent

Trying to attach a file from SD Card to email

http://www.anddev.org/code-snippets-for-android-f33/sending-email-with-attachment-using-intent-t11041.html

http://www.toxicbakery.com/android-development/creating-emails-android/

http://android-geek.blogspot.be/2011/04/share-via-email-intent-image-attachment.html

答案 2 :(得分:0)

我想你使用任何第三方库发送邮件。

        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("image/jpg");
        i.putExtra(Intent.EXTRA_EMAIL, new String[] {"someone@gmail.com"} );
        i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
        i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///mnt/sdcard/myImage.gif"));
        startActivity(i);