如何使用Python发送电子邮件? [英] How can I send email using Python?

查看:294
本文介绍了如何使用Python发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用Python发送电子邮件的程序。我从各种论坛中学到的是以下代码:

 #!/ usr / bin / env python 
import smtplib
sender =sachinites@gmail.com
recipients = [abhisheks@cse.iitb.ac.in]
yourname =Abhishek Sagar
recvname =receptionist
sub =测试电子邮件
body =who cares
message =From:+ yourname +\\\

message = message + to:+ recvname +\\\

message = message +Subject:+ sub +\\\

message = message + body
try:
打印发送电子邮件到+ recvname +...,
server = smtplib.SMTP('smtp.gmail.com:587')
username ='XYZ@gmail.com'
password ='*****'
server.ehlo()
server.starttls()
server.login(用户名,密码)
server.sendmail(发件人,接收者,消息)
server.quit()
打印成功发送!
除外:
打印错误:无法发送电子邮件

但是只是打印错误:无法发送电子邮件并退出终端,我该如何解决?



我将最后两行修改为

 除了异常,错误:
print无法发送电子邮件:'%s' str(error)

我收到以下错误信息:

 追溯(最近的最后一次呼叫):
文件./2.py,第45行,< module>
smtpObj = smtplib .SMTP('localhost')
文件/usr/lib/python2.6/smtplib.py,第239行,__init__
(code,msg)= self.connect(host,port)
文件/usr/lib/python2.6/smtplib.py,第295行,连接
self.sock = self._get_socket(host,port,self.timeout)
文件/usr/lib/python2.6/smtplib.py,第273行,_get_socket
返回socket.create_connection((端口,主机),超时)
文件/usr/lib/python2.6/socket.py,行514,在create_connection
raise错误,msg
socket.error:[Errno 111]连接拒绝


解决方案

如果消息头,有效载荷包含非ASCII字符,那么它们应该被编码: / p>

 #!/ usr / bin / env python 
# - * - 编码: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:')
recipient = [login]

#创建消息
msg = MIMEText('message body ... ','plain','utf-8')
msg ['Subject'] = Header('subject ...','utf-8')
msg ['From'] = login
msg ['To'] =,.join(recipient)

#通过gmail发送
s = SMTP_SSL('smtp.gmail.com',465,timeout = 10 )
s.set_debuglev el(1)
try:
s.login(login,password)
s.sendmail(msg ['From'],recipient,msg.as_string())
finally :
s.quit()


I am writing a program that sends an email using 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:

#!/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()

这篇关于如何使用Python发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆