SMTP协议客户端
smtplib 模块定义了一个 SMTP 客户端会话对象:
import smtplib
smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None)
163邮箱的host 和 port:
host:smtp.163.com
port:25
实例化一个SMTP对象:
self.HOST = "smtp.163.com"
self.PORT = 25
self.smtp = smtplib.SMTP(self.HOST, self.PORT)
下文主要用到SMTP对象的login和send_message方法:
self.MAILID = "123456789**@163.com"
self.AUTHCODE = "0123456789101112"
self.smtp.login(self.MAILID, self.AUTHCODE)
self.msg = EmailMessage()
self.smtp.send_message(self.msg)
EmailMessage 邮件信息对象
self.msg = EmailMessage()
self.msg["Subject"] = "Subject"
self.msg["From"] = self.MAILID
self.msg["To"] = "**@***.com,**@***.com"
self.msg.set_content("Hello World!")
关于:email.policy: 策略对象
上面只是发送了简单的文字 下面的方法可以添加附件:
attch_dir = "data"
filenames = os.listdir(attch_dir)
for filename in filenames:
file_path = os.path.join(attch_dir, filename)
ctype, encoding = mimetypes.guess_type(file_path)
if ctype is None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/")
with open(file_path, "rb") as r:
self.msg.add_attachment(
r.read(), maintype=maintype, subtype=subtype, filename=filename)
完整实例代码:
import logging
import os
import smtplib
import mimetypes
from email.message import EmailMessage
from email.parser import Parser
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s>%(message)s", datefmt="%Y-%m-%d %H:%M:%S")
logger = logging.getLogger(__name__)
class EmailClass(object):
"""docstring for EmailClass"""
def __init__(self):
self.HOST = "smtp.163.com"
self.PORT = 25
self.MAILID = "123456789**@163.com"
self.AUTHCODE = "0123456789101112"
self.smtp = smtplib.SMTP(self.HOST, self.PORT)
self.msg = EmailMessage()
def send_Email(self):
self.set_msg()
with self.smtp:
try:
self.smtp.login(self.MAILID, self.AUTHCODE)
except smtplib.SMTPAuthenticationError as e:
logger.error("登录失败:%s", e.args)
else:
self.smtp.send_message(self.msg)
logger.info("发送成功")
def set_msg(self):
"""设置邮件信息对象"""
self.msg["Subject"] = "Subject"
self.msg["From"] = self.MAILID
self.msg["To"] = "**@***.com,**@***.com"
self.msg.set_content("Hello World!")
self.add_attch()
def add_attch(self):
"""
给邮件信息对象添加附件
同目录下data文件夹内的所有文件将被添加到附件
"""
attch_dir = "data"
filenames = os.listdir(attch_dir)
for filename in filenames:
file_path = os.path.join(attch_dir, filename)
ctype, encoding = mimetypes.guess_type(file_path)
if ctype is None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/")
with open(file_path, "rb") as r:
self.msg.add_attachment(
r.read(), maintype=maintype, subtype=subtype, filename=filename)
if __name__ == "__main__":
EmailClass().send_Email()
注意:一定要开启发送邮件账号的smtp协议,并用正确的授权码进行测试。 以上就是关于 Python email模块发送邮件的学习; 如果有什么不对的地方,欢迎指正!
|