我查看了 API 文档和语言指南,但没有看到任何关于在 Dart 中发送电子邮件的内容。我还检查了这个google groups post,但是按照 Dart 标准它已经很老了。
这可能吗?我知道我总是可以使用 Process 类来调用外部程序,但如果有的话,我更喜欢真正的 Dart 解决方案。
我查看了 API 文档和语言指南,但没有看到任何关于在 Dart 中发送电子邮件的内容。我还检查了这个google groups post,但是按照 Dart 标准它已经很老了。
这可能吗?我知道我总是可以使用 Process 类来调用外部程序,但如果有的话,我更喜欢真正的 Dart 解决方案。
有一个名为 的库mailer,它完全符合您的要求:发送电子邮件。
将其设置为您的依赖项pubspec.yaml并运行pub install:
dependencies:
mailer: any
我将举一个在本地 Windows 机器上使用 Gmail 的简单示例:
import 'package:mailer/mailer.dart';
main() {
var options = new GmailSmtpOptions()
..username = 'kaisellgren@gmail.com'
..password = 'my gmail password'; // If you use Google app-specific passwords, use one of those.
// As pointed by Justin in the comments, be careful what you store in the source code.
// Be extra careful what you check into a public repository.
// I'm merely giving the simplest example here.
// Right now only SMTP transport method is supported.
var transport = new SmtpTransport(options);
// Create the envelope to send.
var envelope = new Envelope()
..from = 'support@yourcompany.com'
..fromName = 'Your company'
..recipients = ['someone@somewhere.com', 'another@example.com']
..subject = 'Your subject'
..text = 'Here goes your body message';
// Finally, send it!
transport.send(envelope)
.then((_) => print('email sent!'))
.catchError((e) => print('Error: $e'));
}
这GmailSmtpOptions只是一个助手类。如果要使用本地 SMTP 服务器:
var options = new SmtpOptions()
..hostName = 'localhost'
..port = 25;
您可以在此处查看课程中所有可能的字段SmtpOptions。
这是使用流行的Rackspace Mailgun的示例:
var options = new SmtpOptions()
..hostName = 'smtp.mailgun.org'
..port = 465
..username = 'postmaster@yourdomain.com'
..password = 'from mailgun';
该库还支持 HTML 电子邮件和附件。查看示例以了解如何执行此操作。
我个人mailer在生产中使用 Mailgun。
== 更新答案:
您可以使用来自 pub.dev 的官方邮件程序库:在您的
下方添加邮件程序库dependencies:pubspec.yaml
dependencies:
mailer: ^3.2.1
然后确保导入这两行:
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';
您可以创建此方法并在任何地方使用它:(这是为 Gmail 发送 SMTP 邮件的示例)
void sendMail() async {
String username = 'username@gmail.com';
String password = 'password';
final smtpServer = gmail(username, password);
final equivalentMessage = Message()
..from = Address(username, 'Your name')
..recipients.add(Address('destination@example.com'))
..ccRecipients.addAll([Address('destCc1@example.com'), 'destCc2@example.com'])
..bccRecipients.add('bccAddress@example.com')
..subject = 'Test Dart Mailer library :: :: ${DateTime.now()}'
..text = 'This is the plain text.\nThis is line 2 of the text part.'
..html = "<h1>Test</h1>\n<p>Hey! Here's some HTML content</p>";
await send(equivalentMessage, smtpServer);
}
}
但请确保在您的 Gmail 帐户设置 > 安全性中启用(不太安全的应用程序访问)以成功与您的电子邮件集成并发送此邮件。