SMTP 서버를 어떻게 테스트할 수 있나요?

SMTP 서버를 어떻게 테스트할 수 있나요?

SMTP 서버 정보와 자격 증명을 받았고 작동하는지 테스트하고 싶습니다.

명령줄을 사용하여 Linux에서 SMTP 연결을 쉽게 테스트하려면 어떻게 해야 합니까?

telnet/openssl을 통해 이 작업을 수행할 수 있다는 것을 알고 있지만 이는 매우 복잡해 보입니다.

그렇다면 SMTP 서버를 확인하는 방법은 무엇입니까?

답변1

이 도구는 swaks여기에 유용합니다.

우분투에서는

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

자세한 내용은 매뉴얼 페이지를 확인하세요.

답변2

Telnet/openssl을 통해 이 작업을 수행할 수 있다는 것을 알고 있지만 이는 매우 복잡해 보입니다.

아주 쉽습니다. 구글링하면 됩니다SMTP 명령, 문제 없이 사용할 수 있습니다. 자신의 질문에 답변한 대로 SWAKS를 사용할 수 있습니다. 다음은 몇 가지 대체 옵션입니다.


다음은 일부 SMTP 명령입니다.

각 명령은 이메일을 전달하기 위해 SMTP 프로토콜을 통해 두 서버 간의 일반적인 통신 순서로 사용됩니다.

헬리콥터
첫 번째 SMTP 명령입니다. 보낸 사람 서버를 식별하는 대화를 시작하고 일반적으로 도메인 이름이 뒤에옵니다.

엘로
서버가 확장된 SMTP 프로토콜을 사용하고 있음을 기반으로 하는 대화를 시작하는 대체 명령입니다.

메일 보낸 사람
이 SMTP 명령을 사용하면 작업이 시작됩니다. 발신자는 "보낸 사람" 필드에 원본 이메일 주소를 명시하고 실제로 이메일 전송을 시작합니다.

RCPT 대상
이메일 수신자를 식별합니다. 둘 이상이면 명령은 단순히 주소별로 반복됩니다.

크기
이 SMTP 명령은 첨부된 이메일의 예상 크기(바이트 단위)를 원격 서버에 알립니다. 또한 서버에서 허용할 메시지의 최대 크기를 보고하는 데 사용할 수도 있습니다.

데이터
DATA 명령을 사용하면 이메일 내용이 전송되기 시작합니다. 일반적으로 서버에서 제공하는 354 응답 코드가 뒤따라 실제 전송을 시작할 수 있는 권한을 부여합니다.

VRFY
서버는 특정 이메일 주소나 사용자 이름이 실제로 존재하는지 확인하라는 요청을 받습니다.

회전하다
이 명령은 새로운 연결을 실행할 필요 없이 클라이언트와 서버 간의 역할을 전환하는 데 사용됩니다.

인증
AUTH 명령을 사용하면 클라이언트는 사용자 이름과 비밀번호를 제공하여 서버에 자신을 인증합니다. 이는 적절한 전송을 보장하는 또 다른 보안 계층입니다.

RSET
이는 진행 중인 이메일 전송이 종료될 것임을 서버에 전달하지만 SMTP 대화는 닫히지 않습니다(QUIT의 경우처럼).

EXPN
이 SMTP 명령은 메일링 리스트 식별에 대한 확인을 요청합니다.

돕다
성공적인 이메일 전송에 도움이 될 수 있는 일부 정보에 대한 고객의 요청입니다.

그만두다
SMTP 대화를 종료합니다.


OpenSSL, 테스트sl.sh 및 GnuTLS

당신이 사용할 수있는openssl s_client, 다음과 같은 명령을 실행하여:

openssl s_client -starttls smtp -connect mail.example.com:587

다음과 같은 도구를 사용할 수도 있습니다.테스트sl.sh로컬에서 호스팅되는 경우에도 SMTP 서버에서 SSL/TLS를 테스트하기 위한 것입니다. 다운로드한 후 압축을 풀고 testsl.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은 smtplibSMTP 또는 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입니다.

  • local_hostname− SMTP 서버가 로컬 컴퓨터에서 실행 중인 경우 옵션으로 localhost만 지정할 수 있습니다.

SMTP 개체에는 sendmail일반적으로 메시지 메일링 작업을 수행하는 데 사용되는 인스턴스 메서드가 있습니다. 세 가지 매개변수가 필요합니다.

  • The sender - 보낸 사람의 주소가 포함된 문자열입니다.

  • The Receivers - 각 수신자에 대해 하나씩 문자열 목록입니다.

  • 메시지 - 다양한 RFC에 지정된 형식의 문자열로 된 메시지입니다.

다음은 Python 스크립트를 사용하여 하나의 이메일을 보내는 간단한 방법입니다. 한번 해보세요 -

#!/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"

여기에서는 헤더 형식을 올바르게 지정하면서 삼중따옴표를 사용하여 메시지에 기본 전자 메일을 배치했습니다. 이메일에는 보낸 사람, 받는 사람 및 제목 헤더가 필요하며, 이메일 본문과 빈 줄로 구분됩니다.

메일을 보내려면 smtpObj를 사용하여 로컬 시스템의 SMTP 서버에 연결합니다. 그런 다음 메시지, 보낸 사람 주소 및 대상 주소와 함께 sendmail 메서드를 매개 변수로 사용합니다(보낸 사람 주소와 받는 사람 주소가 전자 메일 자체 내에 있더라도 항상 메일을 라우팅하는 데 사용되는 것은 아닙니다).

로컬 컴퓨터에서 SMTP 서버를 실행하지 않는 경우 smtplib 클라이언트를 사용하여 원격 SMTP 서버와 통신할 수 있습니다. 웹메일 서비스(예: gmail 또는 Yahoo! Mail)를 사용하지 않는 한, 이메일 제공업체는 다음과 같이 발신 메일 서버 세부정보를 제공해야 합니다.

mail = smtplib.SMTP('smtp.gmail.com', 587)

Python을 사용하여 HTML 이메일 보내기 Python을 사용하여 문자 메시지를 보내면 모든 내용이 단순 텍스트로 처리됩니다. 문자 메시지에 HTML 태그를 포함하더라도 단순 텍스트로 표시되며 HTML 태그는 HTML 구문에 따라 형식이 지정되지 않습니다. 그러나 Python은 HTML 메시지를 실제 HTML 메시지로 보내는 옵션을 제공합니다.

전자 메일 메시지를 보내는 동안 HTML 전자 메일을 보내기 위한 Mime 버전, 콘텐츠 유형 및 문자 집합을 지정할 수 있습니다.

다음은 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로 설정해야 합니다. 그런 다음 텍스트와 첨부 섹션을 경계 내에서 지정할 수 있습니다.

경계는 두 개의 하이픈과 그 뒤에 오는 고유 번호로 시작되며 전자 메일의 메시지 부분에는 나타날 수 없습니다. 이메일의 마지막 섹션을 나타내는 최종 경계도 두 개의 하이픈으로 끝나야 합니다.

첨부파일은 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")

SWAK:

설치하려면:

  • 우분투:sudo apt install swaks
  • CentOS: 첫 번째: sudo yum install epel-releasesudo 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.

MXToolBox

MXToolBox를 사용할 수 있습니다.이메일 서버 테스트때때로 유용할 수 있는 일부 테스트의 경우에는 수행할 작업을 지정할 수 없습니다. 따라서 위의 내용을 사용하는 것이 좋습니다.

아니면 그냥 mail명령을 사용하세요...

답변3

여러 가지 방법으로 테스트할 수 있습니다.

  1. 이미 언급한 대로 Python 라이브러리를 사용합니다.
  2. sendmail 클라이언트를 사용하여 smpt 서버도 테스트하십시오.
  3. 또한 postfix와 dovcot을 설정하여 메일 작업을 수행할 수도 있습니다.

관련 정보