使用SMTP从Python发送邮件

时间:2022-11-15 12:17:32

I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?

我正在使用以下方法使用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()

10 个解决方案

#1


96  

The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.

我使用的脚本非常相似;我在这里发布它作为如何使用电子邮件。*模块生成MIME消息的示例;因此可以轻松修改此脚本以附加图片等。

I rely on my ISP to add the date time header.

我依靠我的ISP添加日期时间标题。

My ISP requires me to use a secure smtp connection to send mail, I rely on the ssmtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)

我的ISP要求我使用安全的smtp连接来发送邮件,我依赖ssmtplib模块(可从http://www1.cs.columbia.edu/~db2501/ssmtplib.py下载)

As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.

与在脚本中一样,用于在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 Exception, exc:
    sys.exit( "mail failed; %s" % str(exc) ) # give a error message

#2


70  

The method I commonly use...not much different but a little bit

我常用的方法......差别不大但有点不同

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()

That's it

而已

#3


20  

Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:

此外,如果您想使用TLS而不是SSL执行smtp auth,那么您只需更改端口(使用587)并执行smtp.starttls()。这对我有用:

...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
...

#4


6  

The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.

我看到的主要问题是你没有处理任何错误:.login()和.sendmail()都记录了他们可以抛出的异常,似乎.connect()必须有一些方法来表明它是无法连接 - 可能是底层套接字代码抛出的异常。

#5


5  

Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.

确保没有任何阻止SMTP的防火墙。我第一次尝试发送电子邮件时,它被Windows防火墙和迈克菲阻止 - 永远都找到了它们。

#6


5  

What about this?

那这个呢?

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()

#7


5  

following code is working fine for me:

以下代码对我来说很好:

import smtplib

to = 'mkyong2002@yahoo.com'
gmail_user = 'mkyong2002@gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo() # extra characters to permit edit
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.quit()

Ref: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/

参考:http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/

#8


3  

You should make sure you format the date in the correct format - RFC2822.

您应该确保以正确的格式格式化日期 - RFC2822。

#9


2  

See all those lenghty answers? Please allow me to self promote by doing it all in a couple of lines.

看到所有那些长长的答案?请允许我通过几行完成这一切来自我推销。

Import and Connect:

导入和连接:

import yagmail
yag = yagmail.SMTP('john@doe.net', host = 'YOUR.MAIL.SERVER', port = 26)

Then it is just a one-liner:

然后它只是一个单行:

yag.send('foo@bar.com', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n')

It will actually close when it goes out of scope (or can be closed manually). Furthermore, it will allow you to register your username in your keyring such that you do not have to write out your password in your script (it really bothered me prior to writing yagmail!)

它实际上会在超出范围时关闭(或者可以手动关闭)。此外,它允许您在密钥环中注册您的用户名,这样您就不必在脚本中写出密码了(在写yagmail之前它确实困扰我!)

For the package/installation, tips and tricks please look at git or pip, available for both Python 2 and 3.

有关软件包/安装,提示和技巧,请查看git或pip,适用于Python 2和3。

#10


0  

you can do like that

你可以这样做

import smtplib
from email.mime.text import MIMEText
from email.header import Header


server = smtplib.SMTP('mail.servername.com', 25)
server.ehlo()
server.starttls()

server.login('username', 'password')
from = 'me@servername.com'
to = 'mygfriend@servername.com'
body = 'That A Message For My Girl Friend For tell Him If We will go to eat Something This Nigth'
subject = 'Invite to A Diner'
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
message = msg.as_string()
server.sendmail(from, to, message)

#1


96  

The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.

我使用的脚本非常相似;我在这里发布它作为如何使用电子邮件。*模块生成MIME消息的示例;因此可以轻松修改此脚本以附加图片等。

I rely on my ISP to add the date time header.

我依靠我的ISP添加日期时间标题。

My ISP requires me to use a secure smtp connection to send mail, I rely on the ssmtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)

我的ISP要求我使用安全的smtp连接来发送邮件,我依赖ssmtplib模块(可从http://www1.cs.columbia.edu/~db2501/ssmtplib.py下载)

As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.

与在脚本中一样,用于在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 Exception, exc:
    sys.exit( "mail failed; %s" % str(exc) ) # give a error message

#2


70  

The method I commonly use...not much different but a little bit

我常用的方法......差别不大但有点不同

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()

That's it

而已

#3


20  

Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:

此外,如果您想使用TLS而不是SSL执行smtp auth,那么您只需更改端口(使用587)并执行smtp.starttls()。这对我有用:

...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
...

#4


6  

The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.

我看到的主要问题是你没有处理任何错误:.login()和.sendmail()都记录了他们可以抛出的异常,似乎.connect()必须有一些方法来表明它是无法连接 - 可能是底层套接字代码抛出的异常。

#5


5  

Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.

确保没有任何阻止SMTP的防火墙。我第一次尝试发送电子邮件时,它被Windows防火墙和迈克菲阻止 - 永远都找到了它们。

#6


5  

What about this?

那这个呢?

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()

#7


5  

following code is working fine for me:

以下代码对我来说很好:

import smtplib

to = 'mkyong2002@yahoo.com'
gmail_user = 'mkyong2002@gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo() # extra characters to permit edit
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.quit()

Ref: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/

参考:http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/

#8


3  

You should make sure you format the date in the correct format - RFC2822.

您应该确保以正确的格式格式化日期 - RFC2822。

#9


2  

See all those lenghty answers? Please allow me to self promote by doing it all in a couple of lines.

看到所有那些长长的答案?请允许我通过几行完成这一切来自我推销。

Import and Connect:

导入和连接:

import yagmail
yag = yagmail.SMTP('john@doe.net', host = 'YOUR.MAIL.SERVER', port = 26)

Then it is just a one-liner:

然后它只是一个单行:

yag.send('foo@bar.com', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n')

It will actually close when it goes out of scope (or can be closed manually). Furthermore, it will allow you to register your username in your keyring such that you do not have to write out your password in your script (it really bothered me prior to writing yagmail!)

它实际上会在超出范围时关闭(或者可以手动关闭)。此外,它允许您在密钥环中注册您的用户名,这样您就不必在脚本中写出密码了(在写yagmail之前它确实困扰我!)

For the package/installation, tips and tricks please look at git or pip, available for both Python 2 and 3.

有关软件包/安装,提示和技巧,请查看git或pip,适用于Python 2和3。

#10


0  

you can do like that

你可以这样做

import smtplib
from email.mime.text import MIMEText
from email.header import Header


server = smtplib.SMTP('mail.servername.com', 25)
server.ehlo()
server.starttls()

server.login('username', 'password')
from = 'me@servername.com'
to = 'mygfriend@servername.com'
body = 'That A Message For My Girl Friend For tell Him If We will go to eat Something This Nigth'
subject = 'Invite to A Diner'
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
message = msg.as_string()
server.sendmail(from, to, message)