想要用python给某个邮箱,发送邮件。
python send email
18.1.11. email: Examples — Python 2.7.14 documentation
结果:
smtpObj = smtplib.SMTP(‘localhost’)
直接就异常了:
smtpObj = smtplib.SMTP(‘localhost’)
File “/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py”, line 256, in __init__
(code, msg) = self.connect(host, port)
File “/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py”, line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File “/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py”, line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File “/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py”, line 575, in create_connection
raise err
socket.error: [Errno 61] Connection refused
很明显,此处没有安装对应邮件服务器。
所以要去参考:
去找此处163邮箱的smtp地址
python 163 smtp
Python使用SMTP发送邮件(163,yeah等网易邮箱已测试可以) – CSDN博客
Python通过网易的SMTP发送邮件 – Python XYZ数据驿站
调试期间,密码错误时去登录会出错:
smtpObj.login(sender, senderPassword)
File “/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py”, line 622, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, ‘Error: authentication failed’)
然后用代码:
def sendNotifMail(gCfg, notifType, productName=””, notifContent=””):
“””
send email notification to user
:param notifType:
:param notifContent:
:return:
“””
logging.debug(“notifType=%s, productName=%s, notifContent=%s”, notifType, productName, notifContent)
sender = gCfg[“notification”][“sender”][“email”]
senderPassword = gCfg[“notification”][“sender”][“password”]
senderName = gCfg[“notification”][“sender”][“username”]
receiver = gCfg[“notification”][“receiver”][“email”]
receiverName = gCfg[“notification”][“receiver”][“username”]
receivers = [receiver]
# receiversName = [receiverName]
title = “[%s] %s” % (notifType, productName)
senderNameAddr = “%s <%s>” % (senderName, sender)
receiverNameAddr = “%s <%s>” % (receiverName, receiver)
# message = “””From: %s <%s>
# To: %s <%s>
# Subject: %s
#
# %s
# “”” % (senderName, sender, receiverName, receiver, title, body)
def _format_addr(nameAndAddress):
“””
format email address
:param nameAndAddress: email name and address
:return:
“””
name, addr = parseaddr(nameAndAddress)
return formataddr(( \
Header(name, ‘utf-8’).encode(), \
addr.encode(‘utf-8’) if isinstance(addr, unicode) else addr))
msg = MIMEText(notifContent, _subtype=”plain”, _charset=”utf-8″)
msg[“From”] = _format_addr(senderNameAddr)
msg[“To”] = _format_addr(receiverNameAddr)
titleHeader = Header(title, “utf-8”)
encodedTitleHeader = titleHeader.encode()
msg[‘Subject’] = encodedTitleHeader
msgStr = msg.as_string()
smtpServer = “smtp.163.com”
smtpPort = 25
# try:
# smtpObj = smtplib.SMTP(‘localhost’)
smtpObj = smtplib.SMTP(smtpServer, smtpPort)
smtpObj.set_debuglevel(1)
smtpObj.login(sender, senderPassword)
smtpObj.sendmail(sender, receivers, msgStr)
logging.info(“Successfully sent email: message=%s”, msgStr)
# except smtplib.SMTPException:
# logging.error(“Fail to sent email: message=%s”, message)
return
输出log:
send: ‘ehlo licrifandeMacBook-Pro.local\r\n’
reply: ‘250-mail\r\n’
reply: ‘250-PIPELINING\r\n’
reply: ‘250-AUTH LOGIN PLAIN\r\n’
reply: ‘250-AUTH=LOGIN PLAIN\r\n’
reply: ‘250-coremail 1Uxr2xKj7kG0xkI17xGrU7I0s8FY2U3Uj8Cz28x1UUUUU7Ic2I0Y2UrSxCK9UCa0xDrUUUUj\r\n’
reply: ‘250-STARTTLS\r\n’
reply: ‘250 8BITMIME\r\n’
reply: retcode (250); Msg: mail
PIPELINING
AUTH LOGIN PLAIN
AUTH=LOGIN PLAIN
coremail 1Uxr2xKj7kG0xkI17xGrU7I0s8FY2U3Uj8Cz28x1UUUUU7Ic2I0Y2UrSxCK9UCa0xDrUUUUj
STARTTLS
8BITMIME
send: ‘AUTH PLAIN AGNyaWZhbjIwMDNAMTYzLmNvbQAqMWxpbWFvbGluMSo=\r\n’
reply: ‘235 Authentication successful\r\n’
reply: retcode (235); Msg: Authentication successful
send: u’mail FROM:<[email protected]>\r\n’
reply: ‘250 Mail OK\r\n’
reply: retcode (250); Msg: Mail OK
send: u’rcpt TO:<[email protected]>\r\n’
reply: ‘250 Mail OK\r\n’
reply: retcode (250); Msg: Mail OK
send: ‘data\r\n’
reply: ‘354 End data with <CR><LF>.<CR><LF>\r\n’
reply: retcode (354); Msg: End data with <CR><LF>.<CR><LF>
data: (354, ‘End data with <CR><LF>.<CR><LF>’)
send: ‘Content-Type: text/plain; charset=”utf-8″\r\nMIME-Version: 1.0\r\nContent-Transfer-Encoding: base64\r\nFrom: Crifan2003 <[email protected]>\r\nTo: green waste <[email protected]>\r\nSubject: =?utf-8?q?=5BhighPrice=5D_Dell_XPS_13_XPS9360-5797SLV-PUS_Laptop?=\r\n\r\nTm90IGJ1eSAnRGVsbCBYUFMgMTMgWFBTOTM2MC01Nzk3U0xWLVBVUyBMYXB0b3AnIGZvciBjdXJy\r\nZW50IHByaWNlICQ2OTkuMDAgPiBleHBlY3RlZCBwcmljZSAkNTk5LjAwLiBhbmQgc2F2ZSBmb3Ig\r\nbGF0ZXIgcHJvY2Vzcw==\r\n.\r\n’
reply: ‘250 Mail OK queued as smtp8,DMCowABXdfGHsyZa2AIHCg–.30514S2 1512485836\r\n’
reply: retcode (250); Msg: Mail OK queued as smtp8,DMCowABXdfGHsyZa2AIHCg–.30514S2 1512485836
data: (250, ‘Mail OK queued as smtp8,DMCowABXdfGHsyZa2AIHCg–.30514S2 1512485836’)
2017/12/05 10:57:19 LINE 473 INFO Successfully sent email: message=Content-Type: text/plain; charset=”utf-8″
MIME-Version: 1.0
Content-Transfer-Encoding: base64
From: Crifan2003 <[email protected]>
To: green waste <[email protected]>
Subject: =?utf-8?q?=5BhighPrice=5D_Dell_XPS_13_XPS9360-5797SLV-PUS_Laptop?=
Tm90IGJ1eSAnRGVsbCBYUFMgMTMgWFBTOTM2MC01Nzk3U0xWLVBVUyBMYXB0b3AnIGZvciBjdXJy
ZW50IHByaWNlICQ2OTkuMDAgPiBleHBlY3RlZCBwcmljZSAkNTk5LjAwLiBhbmQgc2F2ZSBmb3Ig
bGF0ZXIgcHJvY2Vzcw==
成功发送邮件:
发件人的发件箱中有对应邮件:
收件人的收件箱中也可以收到邮件:
再去调试代码,使得其支持html
【总结】
代码:
# debug send email
productName = “Dell XPS 13 XPS9360-5797SLV-PUS Laptop”
productUrl = “https://www.microsoft.com/en-us/store/d/dell-xps-13-xps-9360-laptop-pc/8q17384grz37/GV5D?activetab=pivot%253aoverviewtab”
notifType = “HighPrice”
title = “[%s] %s” % (notifType, productName)
notifContent = “””
<html>
<body>
<h1>%s</h1>
<p>Not buy <a href=”%s”>%s</a> for current price <b>$699.00</b> > expected price <b>$599.00</b></p>
<p>So save for later process</p>
</body>
</html>
“”” % (title, productUrl, productName)
sendEmail(gCfg, title=title, msgContent=notifContent)
def sendEmail(gCfg, title=””, msgContent=””):
“””
send email
:param title:
:param msgContent:
:return:
“””
logging.debug(“title=%s, msgContent=%s”, title, msgContent)
sender = gCfg[“notification”][“sender”][“email”]
senderPassword = gCfg[“notification”][“sender”][“password”]
senderName = gCfg[“notification”][“sender”][“username”]
receiver = gCfg[“notification”][“receiver”][“email”]
receiverName = gCfg[“notification”][“receiver”][“username”]
receivers = [receiver]
# receiversName = [receiverName]
senderNameAddr = “%s <%s>” % (senderName, sender)
receiverNameAddr = “%s <%s>” % (receiverName, receiver)
def _format_addr(nameAndAddress):
“””
format email address
:param nameAndAddress: email name and address
:return:
“””
name, addr = parseaddr(nameAndAddress)
return formataddr(( \
Header(name, ‘utf-8’).encode(), \
addr.encode(‘utf-8’) if isinstance(addr, unicode) else addr))
# msg = MIMEText(msgContent, _subtype=”plain”, _charset=”utf-8″)
msg = MIMEText(msgContent, _subtype=”html”, _charset=”utf-8″)
msg[“From”] = _format_addr(senderNameAddr)
msg[“To”] = _format_addr(receiverNameAddr)
titleHeader = Header(title, “utf-8”)
encodedTitleHeader = titleHeader.encode()
msg[‘Subject’] = encodedTitleHeader
msgStr = msg.as_string()
smtpServer = “smtp.163.com”
smtpPort = 25
# try:
# smtpObj = smtplib.SMTP(‘localhost’)
smtpObj = smtplib.SMTP(smtpServer, smtpPort)
smtpObj.set_debuglevel(1)
smtpObj.login(sender, senderPassword)
smtpObj.sendmail(sender, receivers, msgStr)
logging.info(“Successfully sent email: message=%s”, msgStr)
# except smtplib.SMTPException:
# logging.error(“Fail to sent email: message=%s”, message)
return
效果:
后续再继续优化发送邮件的函数。
支持http/https
支持plain/html
【后记】
后续优化好了,代码详见:
【已解决】Python中smtp如何发送多个收件人地址且带名字的且可以被格式化
转载请注明:在路上 » 【已解决】Python中给某邮箱发送邮件