我有使用Gmail帐户发送电子邮件的工作代码,现在我只想使用没有用户交互的代码进行附件。
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){
}
}
如果您想从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..."));
}
用于发送带附件的电子邮件的安卓意图
使用 Intent 的 Android 多个电子邮件附件
尝试将文件从SD卡附加到电子邮件
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
您没有使用任何第三方库来发送邮件。
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);