使用AsyncTask进行发送邮件与附件
时间: 2023-12-27 08:04:33 浏览: 71
android 下gmail邮件包括附件发送和接收
4星 · 用户满意度95%
使用AsyncTask发送邮件和附件的步骤如下:
1. 在AndroidManifest.xml文件中添加权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
2. 创建一个类继承自AsyncTask,用于在后台线程执行邮件发送操作。
```java
public class SendMailTask extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
private String mRecipient;
private String mSubject;
private String mBody;
private ArrayList<String> mAttachments;
public SendMailTask(Context context, String recipient, String subject, String body, ArrayList<String> attachments) {
mContext = context;
mRecipient = recipient;
mSubject = subject;
mBody = body;
mAttachments = attachments;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
// 创建一个邮件对象
MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
// 设置发件人
message.setFrom(new InternetAddress("你的邮箱地址"));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mRecipient));
// 设置主题
message.setSubject(mSubject);
// 创建一个MimeMultipart对象用于存放邮件的各个部分
MimeMultipart multipart = new MimeMultipart();
// 创建一个MimeBodyPart对象用于存放邮件正文
MimeBodyPart bodyPart = new MimeBodyPart();
// 设置邮件正文内容和格式
bodyPart.setContent(mBody, "text/html;charset=utf-8");
// 将邮件正文部分添加到MimeMultipart对象中
multipart.addBodyPart(bodyPart);
// 添加附件
if (mAttachments != null && mAttachments.size() > 0) {
for (String attachment : mAttachments) {
// 创建一个MimeBodyPart对象用于存放附件
MimeBodyPart attachmentPart = new MimeBodyPart();
// 读取附件文件
File file = new File(attachment);
// 将附件添加到MimeBodyPart对象中
attachmentPart.attachFile(file);
// 将附件部分添加到MimeMultipart对象中
multipart.addBodyPart(attachmentPart);
}
}
// 将MimeMultipart对象设置为邮件内容
message.setContent(multipart);
// 发送邮件
Transport.send(message, "你的邮箱地址", "你的邮箱密码");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
Toast.makeText(mContext, "邮件发送成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "邮件发送失败!", Toast.LENGTH_SHORT).show();
}
}
}
```
3. 在Activity中调用SendMailTask并传入相应的参数。
```java
public class MainActivity extends AppCompatActivity {
private Button mSendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendButton = findViewById(R.id.send_button);
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 收件人地址
String recipient = "收件人地址";
// 邮件主题
String subject = "邮件主题";
// 邮件正文
String body = "邮件正文";
// 附件列表
ArrayList<String> attachments = new ArrayList<>();
attachments.add("/sdcard/attachment1.jpg");
attachments.add("/sdcard/attachment2.docx");
// 发送邮件
new SendMailTask(MainActivity.this, recipient, subject, body, attachments).execute();
}
});
}
}
```
阅读全文