SMTP サーバー情報と資格情報を受け取ったので、それらが機能するかどうかをテストしたいと思います。
コマンドラインを使用して Linux 上の SMTP 接続を簡単にテストするにはどうすればよいですか?
telnet / openssl 経由でこれを実行できることはわかっていますが、これは非常に複雑に思えます。
では、SMTP サーバーを確認するにはどうすればよいでしょうか?
答え1
ここでこのツールがswaks
役立ちます
Ubuntuでは
apt install swaks
その後、コマンドを実行するとSMTPダイアログが表示されます。
$ swaks --to [email protected] --server smtp.ionos.de:587
=== Trying smtp.ionos.de:587...
=== Connected to smtp.ionos.de.
<- 220 kundenserver.de (mreue106) Nemesis ESMTP Service ready
-> EHLO lafto
<- 250-kundenserver.de Hello example [<IP redacted>]
<- 250-8BITMIME
<- 250-AUTH LOGIN PLAIN
<- 250-SIZE 140000000
<- 250 STARTTLS
-> MAIL FROM:<[email protected]>
<** 530 Authentication required
-> QUIT
<- 221 kundenserver.de Service closing transmission channel
=== Connection closed with remote host.
ご覧のとおり、認証が必要です。これが、
$ swaks --to [email protected] --server smtp.ionos.de:587 --auth LOGIN
Username: foo
Password: bar
詳細についてはmanページを確認してください
答え2
telnet / openssl経由でこれを行うことはできますが、非常に複雑に思えます
非常に簡単です。グーグルで検索するだけですSMTP コマンド、問題なく使用できます。ご自身の質問に回答されているように、SWAKS を使用できます。代替オプションをいくつか示します。
これらはいくつかの SMTP コマンドです:
各コマンドは、電子メールを配信するために、SMTP プロトコルを介して 2 つのサーバー間で行われる通常の通信シーケンスで使用されます。
こんにちは
これは最初の SMTP コマンドです。送信元サーバーを識別する会話を開始し、通常はドメイン名が続きます。
えーろ
サーバーが拡張 SMTP プロトコルを使用していることを前提として、会話を開始するための代替コマンド。
メール送信元
この SMTP コマンドにより操作が開始されます。送信者は「From」フィールドに送信元の電子メール アドレスを指定し、実際に電子メールの転送を開始します。
RCPTへ
これは電子メールの受信者を識別します。受信者が複数いる場合は、コマンドがアドレスごとに繰り返されます。
サイズ
この SMTP コマンドは、添付された電子メールの推定サイズ (バイト単位) をリモート サーバーに通知します。また、サーバーが受け入れるメッセージの最大サイズを報告するためにも使用できます。
データ
DATA コマンドにより、電子メールの内容の転送が開始されます。通常、その後にサーバーから 354 応答コードが返され、実際の送信を開始する許可が与えられます。
VRFY
サーバーは、特定の電子メール アドレスまたはユーザー名が実際に存在するかどうかを確認するように求められます。
振り向く
このコマンドは、新しい接続を実行する必要なく、クライアントとサーバー間の役割を反転するために使用されます。
認証
AUTH コマンドを使用すると、クライアントはユーザー名とパスワードを入力してサーバーに認証します。これは、適切な送信を保証するもう 1 つのセキュリティ レイヤーです。
RSET
SMTP 会話は閉じられませんが (QUIT の場合のように)、進行中の電子メール送信が終了することをサーバーに通知します。
エクスパン
この SMTP コマンドは、メーリング リストの識別についての確認を求めます。
ヘルプ
これは、電子メールの正常な転送に役立つ情報を求めるクライアントのリクエストです。
やめる
SMTP 会話を終了します。
OpenSSL、testssl.sh、GnuTLS
使用できますopenssl s_client
次のようなコマンドを実行します。
openssl s_client -starttls smtp -connect mail.example.com:587
というツールを使うこともできますテストsl.shSMTP サーバーで SSL/TLS をテストするためのもので、ローカルでホストされている場合でも同様です。ダウンロードしたら、解凍して testssl.sh フォルダーに移動し、次を実行します。
./testssl.sh -t smtp mail.example.com:25
GnuTLS
インストールされている場合は、以下も使用できます:
gnutls-cli mail.example.com -p 25
テルネット
SMTPサーバーにSSL/TLSがない場合は、telnet
Telnet は、このための最も基本的なツールですが、SSL/TLS をサポートしていません。
telnet mail.example.com 25
PHPメーラー
PHPを使用する場合は、PHPメーラー:
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
$mail->addAddress('[email protected]'); // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
// Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
これは質問に対する答えではありませんが、PHPMailer で DKIM を簡単に設定することもできます。
<?php
/**
* This example shows sending a DKIM-signed message with PHPMailer.
* More info about DKIM can be found here: http://www.dkim.org/info/dkim-faq.html
* There's more to using DKIM than just this code - check out this article:
* @see https://yomotherboard.com/how-to-setup-email-server-dkim-keys/
* See also the DKIM_gen_keys example code in the examples folder,
* which shows how to make a key pair from PHP.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
//Usual setup
$mail = new PHPMailer();
$mail->setFrom('[email protected]', 'First Last');
$mail->addAddress('[email protected]', 'John Doe');
$mail->Subject = 'PHPMailer mail() test';
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
//This should be the same as the domain of your From address
$mail->DKIM_domain = 'example.com';
//See the DKIM_gen_keys.phps script for making a key pair -
//here we assume you've already done that.
//Path to your private key:
$mail->DKIM_private = 'dkim_private.pem';
//Set this to your own selector
$mail->DKIM_selector = 'phpmailer';
//Put your private key's passphrase in here if it has one
$mail->DKIM_passphrase = '';
//The identity you're signing as - usually your From address
$mail->DKIM_identity = $mail->From;
//Suppress listing signed header fields in signature, defaults to true for debugging purpose
$mail->DKIM_copyHeaderFields = false;
//Optionally you can add extra headers for signing to meet special requirements
$mail->DKIM_extraHeaders = ['List-Unsubscribe', 'List-Help'];
//When you send, the DKIM settings will be used to sign the message
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
パイソン
(出典:https://www.tutorialspoint.com/python3/python_sending_email.htmリンクを提供したくないので、代わりに、そのページではいつでも 404 エラーが発生する可能性があるため、すべてをここに投稿しました。
Python はsmtplib
、SMTP または ESMTP リスナー デーモンを備えた任意のインターネット マシンにメールを送信するために使用できる SMTP クライアント セッション オブジェクトを定義するモジュールを提供します。
以下は、後で電子メールの送信に使用できる SMTP オブジェクトを作成するための簡単な構文です。
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters −
ホスト− これは SMTP サーバーを実行しているホストです。ホストの IP アドレスまたは example.com のようなドメイン名を指定できます。これはオプションの引数です。
ポート− ホスト引数を指定する場合は、SMTP サーバーがリッスンしているポートを指定する必要があります。通常、このポートは 25 です。
ローカルホスト名− SMTP サーバーがローカル マシン上で実行されている場合は、オプションとして localhost のみを指定できます。
SMTP オブジェクトには と呼ばれるインスタンス メソッドがありsendmail
、これは通常、メッセージをメールで送信する作業に使用されます。このメソッドは 3 つのパラメータを取ります。
送信者 − 送信者のアドレスを含む文字列。
受信者 − 受信者ごとに 1 つずつの文字列のリスト。
メッセージ − さまざまな RFC で指定されている形式の文字列としてのメッセージ。
例
Python スクリプトを使用して 1 通の電子メールを送信する簡単な方法を紹介します。一度試してみてください。
#!/usr/bin/python3
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
ここでは、ヘッダーを正しくフォーマットするように注意しながら、三重引用符を使用して基本的な電子メールをメッセージに配置しました。電子メールには、From、To、および Subject ヘッダーが必要であり、それらは空白行で電子メールの本文から分離されます。
メールを送信するには、smtpObj を使用してローカル マシン上の SMTP サーバーに接続します。次に、メッセージ、送信元アドレス、および送信先アドレスをパラメーターとして sendmail メソッドを使用します (送信元アドレスと送信先アドレスは電子メール自体の中にありますが、メールのルーティングに必ずしも使用されるわけではありません)。
ローカルマシンで SMTP サーバーを実行していない場合は、smtplib クライアントを使用してリモート SMTP サーバーと通信できます。Web メール サービス (Gmail や Yahoo! メールなど) を使用していない限り、電子メール プロバイダーから、送信メール サーバーの詳細が次のように提供されているはずです。
mail = smtplib.SMTP('smtp.gmail.com', 587)
Python を使用して HTML 電子メールを送信する Python を使用してテキスト メッセージを送信すると、すべてのコンテンツが単純なテキストとして扱われます。テキスト メッセージに HTML タグを含めても、単純なテキストとして表示され、HTML タグは HTML 構文に従ってフォーマットされません。ただし、Python には、HTML メッセージを実際の HTML メッセージとして送信するオプションが用意されています。
電子メール メッセージを送信するときに、MIME バージョン、コンテンツ タイプ、および文字セットを指定して HTML 電子メールを送信できます。
例
以下は HTML コンテンツを電子メールで送信する例です。一度試してみてください。
#!/usr/bin/python3
import smtplib
message = """From: From Person <[email protected]>
To: To Person <[email protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
添付ファイルを電子メールで送信する 混合コンテンツを含む電子メールを送信するには、Content-type ヘッダーを multipart/mixed に設定する必要があります。その後、境界内でテキストと添付ファイルのセクションを指定できます。
境界は 2 つのハイフンで始まり、その後に一意の番号が続きます。この番号は電子メールのメッセージ部分には使用できません。電子メールの最後のセクションを示す最後の境界も 2 つのハイフンで終わる必要があります。
添付ファイルは、pack("m")
送信前に Base 64 エンコード機能を使用してエンコードする必要があります。
/tmp/test.txt
例 以下はファイルを添付ファイルとして送信する例です。一度試してみてください。
#!/usr/bin/python3
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = '[email protected]'
reciever = '[email protected]'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print ("Error: unable to send email")
スワックス:
インストールするには:
- Ubuntuの場合:
sudo apt install swaks
- CentOS: まず、、
sudo yum install epel-release
およびsudo yum install swaks
またはsudo dnf install swaks
- アーチリナックス:
sudo pacman -S swaks
次にコマンドを実行すると、SMTP ダイアログが表示されます。
$ swaks --to [email protected] --server smtp.example.com:587
=== Trying smtp.example.com:587...
=== Connected to smtp.example.com.
<- 220 example.com (something) Foo ESMTP Service ready
-> EHLO somenamehere
<- 250-example.com Hello example [<IP redacted>]
<- 250-8BITMIME
<- 250-AUTH LOGIN PLAIN
<- 250-SIZE 140000000
<- 250 STARTTLS
-> MAIL FROM:<[email protected]>
<** 530 Authentication required
-> QUIT
<- 221 example.com Service closing transmission channel
=== Connection closed with remote host.
ご覧のとおり、認証が必要です。これが、
$ swaks --to [email protected] --server mail.example.com:587 --auth LOGIN
Username: yourusername
Password: yourpassword
サーバーがサポートする方法に応じて、を使用して AUTH PLAIN を使用することもできます--auth PLAIN
。 を使用して詳細についてはマニュアル ページを確認してくださいman swaks
。
MXツールボックス
MXToolBoxのメールサーバーテスト一部のテストでは役立つ場合もありますが、それを使って何をしたいのかを指定することはできません。したがって、上記のものを使用する方がよいでしょう。
または、mail
コマンドを使用するだけです...
答え3
複数の方法でテストできます:
- すでに述べたように、Python ライブラリを使用します。
- sendmail クライアントを使用して smpt サーバーもテストします。
- また、メール操作を実行するために postfix と dovcot を設定することもできます。