Sorry, this entry is only available in 日本語.
Tag Archives: mail
Perl: The way to Send Mail
I’ll introduce the way to send mail in Perl. 私はこの仕組みを、サーバの状態を必要な時にメールで通知するスクリプトなどで利用しています。 (ref.: Server Monitoring Script made by me, a Perl beginner)
Environment
Computer which runs perl
I tried in 2 environments.
Case 1
- Ubuntu 15.04
- Perl 5.20.2
Case 2
- EC2 Amazon Linux 2015.03
- Perl 5.16.3
SMTP Server
- EC2 Amazon Linux 2015.03
- Postfix
- Authenticate with password in CRAM-MD5 way
Code
Here’s the most simple sample code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#!/usr/bin/perl use strict; use utf8; use warnings; use Digest::MD5; use Authen::SASL; use Net::SMTP; my $header = "From: from@sample.com"; $header .= "nTo: to@sample.com"; $header .= "nSubject: subject"; $header .= "nMIME-Version: 1.0"; $header .= "nContent-Type: text/plain; charset=UTF-8"; $header .= "nContent-Transfer-Encoding: Base64n"; $smtp = Net::SMTP->new('mail.sample.com', Port => 587); $smtp->auth('user@sample.com', 'password'); $smtp->mail('from@sample.com'); $smtp->to('to@sample.com'); $smtp->data(); $smtp->datasend($header); $smtp->datasend("n"); $smtp->datasend('message body'); $smtp->quit; |
If you don’t require password authentication, there’s no need to use Digest::MD5
or Authen::SASL
, or the line written auth
. But supposing CRAM-MD5 authentication, they are necessary. auth
method of Net::SMTP
requires Authen::SASL
, which requires Digest::MD5
.
Authen::SASL
が入ってないと auth
を実行しても認証がおこなわれません。 Digest::MD5
が入っていないと、 Error: No SASL mechanism found
と表示されます。
パスワードの認証方式は 自動で判別されています。 認証サーバで Digest-MD5 が有効であれば CRAM-MD5 よりも Digest-MD5 を優先的に使います。
そして、認証をするにはインストールしなければならないパッケージがあります。
- For Ubuntu
- libdigest-hmac-perl
- libauthen-sasl-perl
- For Amazon Linux
- perl-Authen-SASL
Amazon Linux の場合、 MD5 のモジュールが入っているパッケージ perl-Digest-MD5 はあらかじめインストールされています。
In many case, perl is installed in advance and Net::SMTP
module is available to use, but authentication requires additional module installation.
python script for confirmation of sending email
Here is the script of python for confirm sending email, which was used when I was establishing mail server on Amazon AWS EC2, on python 2.7.9.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import smtplib from email.MIMEText import MIMEText from email.Utils import formatdate from_addr = 'sender@sender.com' to_addr = 'your_address@you.com' msg = MIMEText("test") msg['Subject'] = 'subject' msg['From'] = from_addr msg['To'] = to_addr msg['Date'] = formatdate() s = smtplib.SMTP() # Set server and port. Localhost and port 25 are set as default. # s.connect([host[, port]]) s.connect() # Login if the server restrict user of sending mail # s.login('user_name', 'password') s.sendmail(from_addr, [to_addr], msg.as_string()) s.close() |