简体   繁体   English

如何使用Python发送电子邮件?

[英]How can I send email using Python?

I am writing a program that sends an email using Python. 我正在编写一个使用Python发送电子邮件的程序。 What I have learned from various forums is the following piece of code: 我从各种论坛中学到的是以下代码:

#!/usr/bin/env python
import smtplib
sender = "sachinites@gmail.com"
receivers = ["abhisheks@cse.iitb.ac.in"]
yourname = "Abhishek Sagar"
recvname = "receptionist"
sub = "Testing email"
body = "who cares"
message = "From: " + yourname + "\n" 
message = message + "To: " + recvname + "\n"
message = message + "Subject: " + sub + "\n" 
message = message + body
try:
    print "Sending email to " + recvname + "...",
    server = smtplib.SMTP('smtp.gmail.com:587')
    username = 'XYZ@gmail.com'  
    password = '*****'  
    server.ehlo()
    server.starttls()  
    server.login(username,password)  
    server.sendmail(sender, receivers, message)         
    server.quit()
    print "successfully sent!"
except  Exception:
    print "Error: unable to send email"

But it is simply printing ""Error: unable to send email" and exits out on the terminal. How might I resolve this? 但它只是打印“”错误:无法发送电子邮件“并退出终端。我怎么解决这个问题?

I modified the last two lines to 我将最后两行修改为

except Exception, error:
    print "Unable to send e-mail: '%s'." % str(error)

I get the following error message : 我收到以下错误消息:

Traceback (most recent call last):
  File "./2.py", line 45, in <module>
    smtpObj = smtplib.SMTP('localhost')
  File "/usr/lib/python2.6/smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python2.6/smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "/usr/lib/python2.6/socket.py", line 514, in create_connection
    raise error, msg
socket.error: [Errno 111] Connection refused

If message headers, payload contain non-ascii characters then they should be encoded: 如果消息头,有效负载包含非ascii字符,那么它们应该被编码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header    import Header
from email.mime.text import MIMEText
from getpass         import getpass
from smtplib         import SMTP_SSL


login, password = 'user@gmail.com', getpass('Gmail password:')
recipients = [login]

# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ", ".join(recipients)

# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
    s.login(login, password)
    s.sendmail(msg['From'], recipients, msg.as_string())
finally:
    s.quit()

If you print the error message, you will likely get a comprehensive description of what error occurred. 如果您打印错误消息,您可能会全面了解发生了什么错误。 Try (no pun intended) this: 尝试(没有双关语)这个:

try:
    # ...
except Exception, error:
    print "Unable to send e-mail: '%s'." % str(error)

If, after reading the error message, you still do not understand your error, please update your question with the error message and we can help you some more. 如果在阅读错误消息后仍然无法理解您的错误,请使用错误消息更新您的问题,我们可以为您提供更多帮助。


Update after additional information : 更多信息后更新

the error message 错误消息

socket.error: [Errno 111] Connection refused socket.error:[Errno 111]连接被拒绝

means the remote end (eg the GMail SMTP server) is refusing the network connection. 表示远程端(例如GMail SMTP服务器)拒绝网络连接。 If you take a look at the smtplib.SMTP constructor , it seems you should change 如果你看看smtplib.SMTP构造函数 ,你似乎应该改变

server = smtplib.SMTP('smtp.gmail.com:587')

to the following. 以下。

server = smtplib.SMTP(host='smtp.gmail.com', port=587)

According to the error message, you use the localhost as the SMTP server, then the connection was refused. 根据错误消息,您使用localhost作为SMTP服务器,然后拒绝连接。 Your localhost didn't have an SMTP sever running I guess, you need to make sure the SMTP server you connect is valid. 您的本地主机没有运行SMTP服务器我想,您需要确保您连接的SMTP服务器有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用python的smtplib,以后如何发送电子邮件? - Using python's smtplib, how can I send an email in the future? 如何在阵列内发送 email 的 email? 在 python 上使用 smptlib - How can I send an email with the email inside of an array? with smptlib on python 如何使用 email 模块通过 Python email 发送文件? - How do I send files in an email by using the Python email module? 如何使用python 3发送电子邮件? - How to send email using python 3? 如何使用 python 日志记录的 SMTPHandler 和 SSL 发送电子邮件 - How can I send an email using python logging's SMTPHandler and SSL 如何使用 Python 从文件夹中发送 email 中的随机 pdf 文件? - How can I send random pdf files in email from a folder using Python? 如何每隔几个小时检查一次文件夹,如果发现使用Python,该如何发送电子邮件? - How can I check a folder every couple hours and send an email if something is found in it, using Python? 如何在 python 中向多个组发送 smtplib 电子邮件? - How can I send an smtplib email to mulitple groups in python? 如何使用 Python + ZC49DFB55F06BB406E2C5CA786F22Z 从 Gmail 发送 email? - How can I send an email from Gmail with Python + Selenium? 如何发送带有Python附件的zip文件的电子邮件? - How can I send an email with a zip file attached in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM