如何在带有 http 的 dart 中使用 mailgun 添加附件?

How to add attachment using mailgun in dart with http?

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

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

您链接的文档说

Important: You must use multipart/form-data encoding when sending attachments.

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

这可以通过以下代码使用您已经在使用的相同 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 字段相同,只需将其添加到 MultipartRequestfields 参数即可。

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

的文件部分

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


如果您想更轻松地完成此操作,可以尝试 mailgun package,它会为您完成所有这些操作。