在Dart中发送SMTP电子邮件

sta*_*tan 11 email dart

我查看了API文档和语言指南,但我没有看到任何关于在Dart中发送电子邮件的信息.我也检查了这个google群组帖子,但Dart标准已经很老了.

这可能吗?我知道我总是可以使用Process类来调用外部程序,但是如果有的话,我更喜欢真正的Dart解决方案.

Kai*_*ren 17

有一个名为的图书馆mailer,它完全符合您的要求:发送电子邮件.

将其设置为您的依赖项pubspec.yaml并运行pub install:

dependencies:
  mailer: any
Run Code Online (Sandbox Code Playgroud)

我将在本地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'));
}
Run Code Online (Sandbox Code Playgroud)

GmailSmtpOptions只是一个帮手类.如果要使用本地SMTP服务器:

var options = new SmtpOptions()
  ..hostName = 'localhost'
  ..port = 25;
Run Code Online (Sandbox Code Playgroud)

您可以在这里获得所有可能的领域中的SmtpOptions类.

以下是使用流行的Rackspace Mailgun的示例:

var options = new SmtpOptions()
  ..hostName = 'smtp.mailgun.org'
  ..port = 465
  ..username = 'postmaster@yourdomain.com'
  ..password = 'from mailgun';
Run Code Online (Sandbox Code Playgroud)

该库还支持HTML电子邮件和附件.查看示例以了解如何执行此操作.

我个人使用mailerMailgun进行生产使用.

  • Dart的包裹管理非常棒.谢谢. (3认同)