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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值