130

SMTPを使用してPythonからメールを送信するには、次の方法を使用しています。それは使用する正しい方法ですか、それとも私が見逃している落とし穴がありますか?

from smtplib import SMTP
import datetime

debuglevel = 0

smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')

from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"

subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

message_text = "Hello\nThis is a mail from your server\n\nBye\n"

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" 
        % ( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
4

14 に答える 14

123

私が使用するスクリプトは非常に似ています。email.* モジュールを使用して MIME メッセージを生成する方法の例として、ここに投稿します。そのため、このスクリプトを簡単に変更して、写真などを添付できます。

日時ヘッダーの追加は ISP に依存しています。

私の ISP では、安全な smtp 接続を使用してメールを送信する必要があります。smtplib モジュール ( http://www1.cs.columbia.edu/~db2501/ssmtplib.pyでダウンロード可能)に依存しています

スクリプトのように、SMTP サーバーでの認証に使用されるユーザー名とパスワード (以下にダミーの値を指定) は、ソースではプレーン テキストです。これはセキュリティ上の弱点です。しかし、最良の代替手段は、これらを保護するためにどれだけ注意する必要があるか (したいですか?) によって異なります。

=======================================

#! /usr/local/bin/python


SMTPserver = 'smtp.att.yahoo.com'
sender =     'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'


content="""\
Test message
"""

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except:
    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
于 2008-09-15T17:24:40.253 に答える
96

私が普段使っている方法・・・大差ないけど少しだけ

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart()
msg['From'] = 'me@gmail.com'
msg['To'] = 'you@gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me@gmail.com', 'mypassword')

mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())

mailserver.quit()

それでおしまい

于 2013-07-11T14:59:54.337 に答える
23

また、SSL ではなく TLS で smtp 認証を行いたい場合は、ポートを変更して (587 を使用)、smtp.starttls() を実行するだけです。これは私のために働いた:

...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
...
于 2008-11-08T20:12:26.547 に答える
6

これはどうですか?

import smtplib

SERVER = "localhost"

FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python's smtplib."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
于 2012-06-27T14:31:09.650 に答える
6

私が見る主な落とし穴は、エラーを処理していないことです。.login()両方.sendmail()とも、スローできる例外を文書化.connect()しており、接続できなかったことを示す何らかの方法が必要なようです-おそらく、基になるソケットによってスローされた例外ですコード。

于 2008-09-15T16:43:36.950 に答える
6

SMTP をブロックするファイアウォールがないことを確認してください。初めて電子メールを送信しようとしたとき、Windows ファイアウォールと McAfee の両方によってブロックされ、両方を見つけるのに時間がかかりました。

于 2008-09-15T16:55:57.047 に答える
4

SMTPを使用してメールを送信するために行ったサンプルコード。

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "sender@email"
receiver_email = "receiver@email"
password = "<your password here>"
message = """ Subject: Hi there

This message is sent from Python."""


# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
server = smtplib.SMTP(smtp_server,port)

try:
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit()
于 2019-04-02T10:55:20.627 に答える
3

日付を正しい形式 ( RFC2822 ) でフォーマットしていることを確認する必要があります。

于 2008-09-15T16:46:00.393 に答える