发送邮件代码
# !/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服务
mail_host = "" # 设置服务器
mail_user = "xxx@" # 用户名
mail_pass = "xxx" # 口令
sender = mail_user
sender_name = "admin" # 显示名称
receiver = 'xxx@'
# 接收邮件,可设置为你的QQ邮箱或者其他邮箱,列表 发送会报错
# 邮件内容
message = MIMEText("正文内容", 'plain', 'utf-8')
message['From'] = "{0}<{1}>".format(sender_name ,sender)
message['To'] = receiver
message['Subject'] = Header("标题", 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receiver, message.as_string())
print "邮件发送成功"
smtpObj.quit()
smtpObj.close()
except smtplib.SMTPException as e:
print "Error: 无法发送邮件", e
封装成简单邮件发送模块
# email_helper.py
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
debug = True # debug开关
def debug_info(text):
if debug == True:
print(text)
class EmailClient(object):
'邮件发送端初始化类'
def __init__(self, smtp_server):
'初始化服务器地址'
self._smtp_server = smtp_server
self.addrs = [] # 邮件地址列表, 格式(addr, name)
def login(self, from_addr, password, from_name=None):
'登录'
self._from_addr = from_addr
self._password = password
if from_name == None:
self._from_name = from_addr
else:
self._from_name = from_name
try:
self.server = smtplib.SMTP(self._smtp_server, 25)
# server.set_debuglevel(1)
self.server.login(self._from_addr, self._password)
except Exception as e:
return -1 # 登录失败
debug_info("登录失败")
else:
return 0 # 登录成功
debug_info("登录成功")
def _send(self, title, text, to_addr, to_name=None):
'发送邮件'
if to_name == None: to_name = to_addr
try:
# 接受方信息
msg = MIMEText(text, 'plain', 'utf-8')
msg['From'] = self._format_addr('%s<%s>' % (
self._from_name, self._from_addr))
msg['To'] = self._format_addr('%s <%s>' % (to_name, to_addr))
msg['Subject'] = Header(title, 'utf-8').encode()
# 发送内容
self.server.sendmail(self._from_addr, to_addr, msg.as_string())
return 0
except Exception as e:
debug_info(e)
return -1
def add_address(self, addr, name=None):
'增加地址到地址列表'
if name == None: name = addr
self.addrs.append((addr, name))
def send_all(self, title, text):
'发送所有人'
success = 0
fail = 0
for addr, name in self.addrs:
ret = self._send(title, text, addr, name)
if ret == 0:
success += 1
else:
fail += 1
return success, fail
def __del__(self):
'析构'
self.server.quit()
def _format_addr(self, s):
'格式化地址'
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
if __name__ == '__main__':
# 邮箱服务器地址
email_client = EmailClient("")
# 登陆,密码或授权码
email_client.login("xxxx@", "password")
# 增加收件人
email_client.add_address("xxx@")
email_client.add_address("email")
email_client.add_address("email")
# 发送
title = "邮件标题"
body = "邮件内容,试试看能不能发送出去"
success, fail = email_client.send_all(title, body)
# 返回发送结果
print("success:", success, "fail:", fail)
实例:整点报时发邮件
引入上面的模块文件,当整点的时候就给自己的邮件发一份邮件,汇报现在时刻
# email_demo.py
from email_helper import EmailClient
from datetime import datetime
import time
email_client = EmailClient("") # 邮箱服务器地址
email_client.login("xxx@", "xxx") # 登陆
email_client.add_address("xxxx@") # 增加收件人
# 发送
while True:
now = datetime.now()
if now.minute == 0 and now.second == 0:
title = "整点时间提醒邮件"
body = "现在时刻:%s"%now
success, fail = email_client.send_all(title, body)
print("success:", success, "fail:", fail) # 返回发送结果
time.sleep(5)
scrapy中发送邮件
如果是使用scrapy 爬虫框架,就比较简单了,直接使用如下代码就行,当然也可以将参数配置到setting文件里,多次调用参数。
ps:单独测试没有成功,运行爬虫项目中测试才行
# -*- coding:utf-8 -*-
# 测试邮箱发送
from scrapy.mail import MailSender
mailer = MailSender(smtphost='',
mailfrom="xxx@",
smtpuser="xxx@",
smtppass="xxxxx",
smtpport=25)
mailer.send(to=["xxx@"],
subject="请查收",
body="hello world")
优化后的简单实用
支持25端口和465端口设置
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
class EmailSender(object):
# 邮箱配置
# 服务器地址
MAIL_HOST = ""
# 服务器端口 25 或者 465(ssl)
MAIL_PORT = 465
# 发件人邮箱账号
MAIL_USER = "xxx@"
# 发件人邮箱密码
MAIL_PASS = "123456"
# 发件人邮箱别名
MAIL_NAME = "xxx"
# 收件人地址
MAIL_TO = "xxx@"
@classmethod
def send(cls, subject, text, to_addrs=None):
msg = cls._get_email(subject, text)
# 发送邮件
if cls.MAIL_PORT == 465:
server = smtplib.SMTP_SSL(cls.MAIL_HOST) # ssl 465端口
else:
server = smtplib.SMTP(cls.MAIL_HOST, cls.MAIL_PORT) # 25端口
# 发送地址
if to_addrs is None:
to_addrs = [cls.MAIL_TO]
server.login(cls.MAIL_USER, cls.MAIL_PASS) # 登录
server.sendmail(cls.MAIL_USER, to_addrs, msg.as_string()) # 发送
server.quit() # 退出
@classmethod
def _get_email(cls, subject, text):
# 构造邮件
msg = MIMEText(text, 'plain', 'utf-8')
# 邮箱昵称、发件人邮箱账号
msg['From'] = formataddr([cls.MAIL_NAME, cls.MAIL_USER])
msg['To'] = formataddr([cls.MAIL_TO, cls.MAIL_TO])
msg['Subject'] = subject
return msg
if __name__ == '__main__':
EmailSender.send("你好", "这是内容")
参考:
- SMTP发送邮件 - 廖雪峰博客
- Python SMTP发送邮件 - 菜鸟教程
- scrapy 发送email