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 <[email protected]>');
  body.putIfAbsent('to', () => '[email protected]');
  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

最佳答案

您链接的文档说

因此,您想要执行MultipartRequest,而不仅仅是普通的发布请求。
使用已使用的相同http包,可以使用以下代码大致完成此操作。

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

var body = <String, dynamic>{};
body.putIfAbsent('from', () => 'John Smith <[email protected]>');
body.putIfAbsent('to', () => '[email protected]');
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参数中,即可完成所有操作。
header 已更改以指示正确的类型。从该路径创建一个MultipartFile,并为其指定字段名称attachment。这被添加到MultipartRequest的文件部分。
然后,该请求将按照与您已经拥有的类似的方式发送和处理。

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

关于http - 如何在带有http的dart中使用Mailgun添加附件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64014177/

10-13 08:39