使用python发送邮件
#coding=utf-8 import smtplib from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage class Send_Email(): def __init__(self, num): self.num = num self.smtp = self.produce_smtp() self.send_email() # 创建一个smtp对象并登录 def produce_smtp(self): # 创建对象 smtp = smtplib.SMTP() # 连接服务器 smtp.connect('smtp.163.com') # 登录邮箱 smtp.login('13349949963@163.com', 'zb') return smtp # 发送邮件 def send_email(self): sender = '13349949963@163.com' #定义发送邮箱地址 receiver = '376100870@qq.com' #定义接收邮箱地址 if self.num == 5: receiver = ['983978082@qq.com', '376100870@qq.com'] msg = self.get_msg(sender, receiver) print(receiver) self.smtp.sendmail(sender, receiver, msg.as_string()) print("发送成功") # 获取发送的信息 def get_msg(self, sender, receiver): subject = '这是邮件主题' msg = self.get_msg_content() msg['From']=sender #一定要指定'From'属性,否则会报554 if self.num == 5: msg["To"] = ",".join(receiver) else: # 多个邮件接收人时,如果报错,可以不指定 msg['To'] = receiver msg['Subject'] = Header(subject, 'utf-8') return msg def get_msg_content(self): if self.num == 1: content = "这是邮件的内容" msg = MIMEText(content, 'plain', 'utf-8') # 第二个参数使用'plain' return msg elif self.num == 2: content = '</pre><h1>这是html格式的邮件内容</h1><pre>' # 参数'html'指定邮件内容格式 msg = MIMEText(content, 'html', 'utf-8') return msg elif self.num == 3: return self.get_pic() elif self.num == 4: return self.get_attachment() elif self.num == 5: content = '<html><h1>这是一封群发邮件</h1></html>' # 定义邮件三大主题 return MIMEText(content, 'html', 'utf-8') def get_pic(self): # subject = '这是邮件主题' # 通过cid将图片文件关联起来 content = '<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!' # 如果存在内嵌资源,至少要定义multipart/related段。本例中html内嵌图片资源,所以使用related msgRoot = MIMEMultipart('related') # msgRoot['Subject'] = subject msgText = MIMEText(content, 'html', 'utf-8') msgRoot.attach(msgText) # 关联邮件内容 # 获取并读取图片文件 fp = open('./1.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', 'image1') msgRoot.attach(msgImage) # 关联图片资源 return msgRoot def get_attachment(self): content = '<html><h1>这是一封带附件的邮件</h1></html>' # 定义邮件三大主题 # 如果一封邮件中含有附件,那邮件的Content-Type域中必须定义multipart/mixed类型 msgRoot = MIMEMultipart('mixed') # 构造邮件正文 msgText = MIMEText(content, 'html', 'utf-8') msgRoot.attach(msgText) fp = open('./1.py', 'rb') msgAtt = MIMEText(fp.read(), 'base64', 'utf-8') msgAtt["Content-Type"] = 'application/octet-stream' msgAtt["Content-Disposition"] = 'attachment; filename="1.py"' msgRoot.attach(msgAtt) return msgRoot # 发送邮件 if __name__=='__main__': ''' 1.文件形式的邮件 2.HTML 形式的邮件 3.带图片的HTML邮件 4.带附件的邮件 5.群发邮件 6.各种元素都包含的邮件 ''' num = int(input("请输入发送邮件的内容:")) Send_Email(num) # 课后作业:发送一封各种元素都包括的群邮件