2013-07-23 24 views
11

私はAPIのドキュメントと言語ガイドを調べましたが、ダーツでメールを送信することについて何も表示されませんでした。私もこのgoogle groups postをチェックしましたが、Dartの標準ではかなり古くなっています。ダーツでSMTPメールを送信

これは可能ですか?私はいつでも外部プログラムを呼び出すためにProcessクラスを使うことができると知っていますが、もしあれば、本当のDartソリューションを好むでしょう。

答えて

17

mailerと呼ばれるライブラリがあります。これは、あなたが求めたことを正確に行います。電子メールを送信します。

あなたpubspec.yamlで依存関係として設定し、それをしてpub installを実行します。

dependencies: 
    mailer: any 

を私はローカルのWindowsマシン上のGmailを使用して簡単な例を与える:

import 'package:mailer/mailer.dart'; 

main() { 
    var options = new GmailSmtpOptions() 
    ..username = '[email protected]' 
    ..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]' 
    ..fromName = 'Your company' 
    ..recipients = ['[email protected]', '[email protected]'] 
    ..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 = '[email protected]' 
    ..password = 'from mailgun'; 

ライブラリが同様にHTMLメールや添付ファイルをサポートしています。それを行う方法については、the exampleをご覧ください。

私は個人的に実用的にMailgunでmailerを使用しています。

+0

参考までに、アプリケーション固有のパスワードに注意してください。彼らは2因子認証を迂回し、名前のような特定のアプリケーションに限定されません。私は決してソースコードに置くつもりはない。 _安全なキーストレージサービスから安全にロードすることができます。 –

+0

多分私は誰もそのようなソースコードを保存することを意図したことを明確にする必要があります!更新された例。 –

+0

Googleの場合、そのようなパスワードを安全に保管することは決してできません。ほとんどの場合、Mailgunのようなほとんどの電子メールサービスの場合のように、電子メールサービス固有のパスワードを保管しています。メモをありがとう。 –

関連する問題