首页 > 解决方案 > 如何在带有http的飞镖中使用mailgun添加附件?

问题描述

Mailgun 官方支持http,但Dart 没有官方包,截止到2020 年9 月,邮件发送成功但附件不见了。注意所有失败的尝试。

import 'dart:io';
import 'package:http/http.dart' as foo;

// must be https for basic auth (un + pw)
const secureProtocol = 'https://';
const host = 'api.mailgun.net/v3/m.givenapp.com/messages';

// basic auth
const userApiKey = 'my api key here'; // pw
const un = 'api';

void main() async {
  //
  const path = 'bin/services/foo.baz.txt';
  var file = File(path);
  print(file.existsSync()); // looks good
  print(file.readAsStringSync()); // looks good
  var list = <String>[];
  list.add(file.readAsStringSync());
  var files = <File>[];
  files.add(file);
  //
  var body = <String, dynamic>{};
  body.putIfAbsent('from', () => 'John Smith <john.smith@example.com>');
  body.putIfAbsent('to', () => 'jane.doe@somehost.com');
  body.putIfAbsent('subject', () => 'test subject  ' + DateTime.now().toIso8601String());
  body.putIfAbsent('text', () => 'body text');

  // fixme
  body.putIfAbsent('attachment', () => '@$path'); // failed
  body.putIfAbsent('attachment', () => path); // failed
  //body.putIfAbsent('attachment', () => file); // failed
  //body.putIfAbsent('attachment', () => list); // failed
  //body.putIfAbsent('attachment', () => files); // failed
  body.putIfAbsent('attachment', () => file.readAsStringSync()); // failed
  //body.putIfAbsent('attachment', () => file.readAsBytesSync()); // failed

  final uri = '$secureProtocol$un:$userApiKey@$host';

  final response = await foo.post(uri, body: body);

  print('Response status: ${response.statusCode}');
  print('Response body: ${response.body}');
}

我想我很接近了。

https://documentation.mailgun.com/en/latest/api-sending.html#sending

标签: httpdartattachmentmailgun

解决方案


您链接的文档说

重要提示:发送附件时必须使用 multipart/form-data 编码。

所以你想做一个MultipartRequest,而不仅仅是一个普通的发布请求。

这可以通过以下代码使用您已经使用的相同 http 包大致完成。

var request = foo.MultipartRequest(
  'POST',
  Uri.parse('$secureProtocol$un:$userApiKey@$host')
);

var body = <String, dynamic>{};
body.putIfAbsent('from', () => 'John Smith <john.smith@example.com>');
body.putIfAbsent('to', () => 'jane.doe@somehost.com');
body.putIfAbsent('subject', () => 'test subject  ' + DateTime.now().toIso8601String());
body.putIfAbsent('text', () => 'body text');

request.fields = body;

request.headers["Content-Type"] = "multipart/form-data";
request.files.add(await http.MultipartFile.fromPath('attachment', path));

var response = await request.send();
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

一切都与添加 from、to、subject 和 text 字段相同,只需将其添加fieldsMultipartRequest.

标题已更改以指示正确的类型。AMultipartFile是从路径创建的,并给定字段名称attachment. 这被添加到MultipartRequest.

然后,该请求将被发送并与您已有的类似处理。


如果您想更轻松地执行此操作,可以尝试使用mailgunpackage,它会为您完成所有这些。


推荐阅读