有一个图书馆叫mailer https://github.com/kaisellgren/mailer,这正是您所要求的:发送电子邮件。
将其设置为您的依赖项pubspec.yaml
并运行pub install
:
dependencies:
mailer: any
我将给出一个在本地 Windows 计算机上使用 Gmail 的简单示例:
import 'package:mailer/mailer.dart';
main() {
var options = new GmailSmtpOptions()
..username = '[email protected] /cdn-cgi/l/email-protection'
..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 = '[email protected] /cdn-cgi/l/email-protection'
..fromName = 'Your company'
..recipients = ['[email protected] /cdn-cgi/l/email-protection', '[email protected] /cdn-cgi/l/email-protection']
..subject = 'Your subject'
..text = 'Here goes your body message';
// Finally, send it!
transport.send(envelope)
.then((_) => print('email sent!'))
.catchError((e) => print('Error: $e'));
}
The GmailSmtpOptions
只是一个辅助类。如果您想使用本地 SMTP 服务器:
var options = new SmtpOptions()
..hostName = 'localhost'
..port = 25;
You can 在这里检查所有可能的字段 https://github.com/kaisellgren/mailer/blob/master/lib/src/smtp/smtp_options.dart in the SmtpOptions
class.
这是一个使用流行的例子机架空间邮件枪 https://mailgun.com/:
var options = new SmtpOptions()
..hostName = 'smtp.mailgun.org'
..port = 465
..username = '[email protected] /cdn-cgi/l/email-protection'
..password = 'from mailgun';
该库还支持 HTML 电子邮件和附件。查看这个例子 https://github.com/kaisellgren/mailer#sending-an-email-with-smtp学习如何做到这一点。
我个人使用mailer
在生产环境中使用 Mailgun。