问题
i have the working code for sending email using gmail account, Now I just want to go for attachment using code without user interaction.
回答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){
}
}
回答2:
If you want to send some files from SDCard, please use these codes:
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
回答3:
I suppose you are not using any third party library to send mails.
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);
来源:https://stackoverflow.com/questions/13560781/attachment-in-gmail-using-code