我浏览了API文档和语言指南,但我没有看到任何关于在Dart中发送电子邮件的信息。我也检查了这个google groups post,但Dart标准已经很老了。
这可能吗?我知道我总是可以使用Process类来调用外部程序,但如果有的话,我更喜欢真正的Dart解决方案。
答案 0 :(得分:18)
有一个名为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
课程中check here for all possible fields。
以下是使用热门Rackspace Mailgun:
的示例var options = new SmtpOptions()
..hostName = 'smtp.mailgun.org'
..port = 465
..username = 'postmaster@yourdomain.com'
..password = 'from mailgun';
该库也支持HTML电子邮件和附件。查看the example以了解如何操作。
我个人在生产中使用mailer
和Mailgun。
答案 1 :(得分:0)
== 更新答案:
您可以使用来自 pub.dev 的官方 mailer 库:
在您的 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 帐户设置 > 安全性中启用 (Less secure app access) 以成功与您的电子邮件集成并发送此邮件。