小方哥哥 2019-06-30
import smtplib from email.mime.text import MIMEText # 发送文本 from email.mime.image import MIMEImage # 发送图片 from email.mime.multipart import MIMEMultipart # 将多个对象结合起来 from email.utils import formataddr from email.header import Header
sender_from = '[email protected]' # 发件人邮箱 sender_to='[email protected]' # 收件人邮箱 # 定义一个函数,接收传入的邮件主题,邮件内容为参数 def send_email(eamil_subject:str,email_content:str)->int: try: # 构造邮件的内容 plain:表示发送的是文本;HTML:表示发送的超文本 message = MIMEText(email_content, 'plain', 'utf-8') # 主题 message['Subject'] = Header(eamil_subject, 'utf-8') message['From'] = formataddr(['icessun', sender_from]) message['To'] = formataddr(['604421385', sender_to]) # 构造发送邮件的对象smtp,实例化SMTP() smtp = smtplib.SMTP() # 连接邮箱服务器 host 和 port smtp.connect('smtp.qq.com', 25) # 可以简写 smtp=smtplib.SMTP('smtp.qq.com',25) # 登陆邮箱 第二个参数是qq邮箱授权码 smtp.login(sender_from, 'xxxxxxxx') # 发送方,接收方(可以有多个['接收地址1','接收地址2',....]),发送的消息(字符串类型,使用邮件格式) # message.as_string() 将MIMEText对象变为str smtp.sendmail(sender_from, sender_to, message.as_string()) # 退出邮箱,结束SMTP会话 smtp.quit() return 0 except: return -1
# 构造邮件的内容 plain:表示发送的是文本;HTML:表示发送的超文本 email_content = '这是发送的文本消息' message = MIMEText(email_content, 'plain', 'utf-8')
# 打开文件所在的位置 send_file=open(r'F:\password.txt').read() # 二进制文件 message = MIMEText(send_file, 'base64', 'utf-8') message['Content-Type'] = 'application/octet-stream' # 内容展示的方式:attachment ,中文名字显示不成功 aaa.txt 英文才能正常显示 # message['Content-Disposition'] = 'attachment;filename="aaa.txt"' message.add_header('Content-Disposition','attachment',filename='aaaa.txt')
message['From'] = Header('python','utf-8') message['To'] = Header('参数', 'utf-8')
# 默认字符编码为 utf-8,第一个参数传入列表[发件人的名字,邮箱地址] message['From'] = formataddr(['hhhh', sender_from]) message['To'] = formataddr(['604421385', sender_to])
message = MIMEMultipart('mixed') # 然后把 邮件的 Subject From To 添加到 message中 message['Subject'] = Header(email_subject,'utf-8') message['From'] = formataddr(['test',sender_from]) message['To'] = formataddr(['接收者',sender_to])
message.attach(text_plain) # MIMEText 对象 message.attach(text_html) # 超文本 message.attach(text_att) # 附件 message.attach(image) # MIMEImage 对象
发送邮件的多功能代码:
代码地址
回复:QQ邮箱 获取