如何从 Flutter Web 应用程序发送电子邮件?

Posted

技术标签:

【中文标题】如何从 Flutter Web 应用程序发送电子邮件?【英文标题】:How to send email from a Flutter Web application? 【发布时间】:2020-05-28 12:50:09 【问题描述】:

我正在尝试使用邮件程序包从 Flutter Web 应用程序发送电子邮件,但出现此错误:

不支持的操作:套接字构造函数

该软件包似乎依赖于 dart:io,Flutter Web 不支持它。这是用于发送电子邮件的代码:

_sendEmail(String body) async 
print('Sending email...');
String username = 'myemail';
String password = 'mypassword';

final smtpServer = gmail(username, password);
final message = Message()
  ..from = Address(username, 'sender_name')
  ..recipients.add('reciever_email')
  ..subject = 'subject'
  ..text = body;

try 
  final sendReport = await send(message, smtpServer);
  print('message sent: $sendReport.toString()');
 catch (e) 
  print('message not sent: $e');
  e.problems.forEach(
    (element) => print('Problem: $element.code: $element.msg')
  );

我已使用占位符作为凭据,我确信它们是正确的。有没有办法从 Flutter Web 应用程序发送电子邮件?

【问题讨论】:

Flutter Web(顾名思义)在 Web 浏览器中作为 javascript 运行,因此仅限于 JavaScript 可以执行的功能。由于 JavaScript 无法创建 TCP 套接字,因此无法在 JavaScript 中实现 SMTP 协议。由于mailer 似乎只能使用 SMTP 发送邮件,因此您需要找到另一个库。您可以查看googleapis 包,它为 Google 服务(如 Google Mail)提供 API。由于这个包通过向 Google 发送 HTTP 请求来工作,因此它可以在 JavaScript 和 Flutter Web 中工作。 还有其他方法吗? .. 我想通过点击按钮自动发送电子邮件 【参考方案1】:

SendGrid(和 MailJet)被设计为只能在服务器上工作,而不是在客户端上工作。 注册https://app.sendgrid.com/

创建 API 密钥 可选:查看文档(https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html)

并使用此代码(将 SENDGRIDAPIKEY 替换为您的 API 密钥):

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

class SendGridUtil 
  static sendRegistrationNotification(String email) async 
    Map<String, String> headers = new Map();
    headers["Authorization"] =
        "Bearer $$$SENDGRIDAPIKEY$$$";
    headers["Content-Type"] = "application/json";

    var url = 'https://api.sendgrid.com/v3/mail/send';
    var response = await http.post(url,
        headers: headers,
        body:
            "\n          \"personalizations\": [\n            \n              \"to\": [\n                \n                  \"email\": \"jerrod@liftaixxx.com\"\n                ,\n                \n                  \"email\": \"darran@gmailxxx.com\"\n                \n              ]\n            \n          ],\n          \"from\": \n            \"email\": \"app@liftaixxx.com\"\n          ,\n          \"subject\": \"New user registration\",\n          \"content\": [\n            \n              \"type\": \"text\/plain\",\n              \"value\": \"New user register: $email\"\n            \n          ]\n        ");
    print('Response status: $response.statusCode');
    print('Response body: $response.body');
  

使用包

flutter_email_sender

例子:

final Email email = Email(
  body: 'Email body',
  subject: 'Email subject',
  recipients: ['example@example.com'],
  cc: ['cc@example.com'],
  bcc: ['bcc@example.com'],
  attachmentPaths: ['/path/to/attachment.zip'],
  isHTML: false,
);

await FlutterEmailSender.send(email);

https://pub.dev/packages/flutter_email_sender/example

使用包

mailto 2.0.0

例子:

import 'dart:io';

import 'package:mailto/mailto.dart';

Future<void> main() async  
  final mailto = Mailto(
    to: [
      'example@example.com',
      'ejemplo@ejemplo.com',
    ],
    cc: [
      'percentage%100@example.com',
      'QuestionMark?address@example.com',
    ],
    bcc: [
      'Mike&family@example.org',
    ],
    subject: 'Let\'s drink a "café"! ☕️ 2+2=4 #coffeeAndMath',
    body:
        'Hello this if the first line!\n\nNew line with some special characters őúóüűáéèßáñ\nEmoji: ???',
  );

  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 3000);
  String renderHtml(Mailto mailto) => '''<html><head><title>mailto example</title></head><body><a href="$mailto">Open mail client</a></body></html>''';
  await for (HttpRequest request in server) 
    request.response
      ..statusCode = HttpStatus.ok
      ..headers.contentType = ContentType.html
      ..write(renderHtml(mailto));
    await request.response.close();
  

https://pub.dev/packages/mailto

https://github.com/smaho-engineering/mailto/blob/master/example/flutter/lib/main.dart

【讨论】:

以上是关于如何从 Flutter Web 应用程序发送电子邮件?的主要内容,如果未能解决你的问题,请参考以下文章

从 Flutter Web 发送邮件

Flask 教程 第十章:邮件支持

Mime 和 Office365

如何从我的 React Web 应用程序发送电子邮件

Flutter Firebase - 点击Firebase发送的电子邮件验证链接时如何打开应用程序?

发送“代表”电子邮件