python使用QQ邮箱实现自动发送邮件
在Python编程中,发送邮件是一项常见的任务,尤其在自动化脚本和系统通知中。本文将详细讲解如何使用Python结合QQ邮箱实现自动发送邮件,并提供三种不同类型的邮件发送方法:普通文本邮件、携带附件的邮件以及携带图片的附件邮件。 发送邮件的主要库是`smtplib`和`email`。在Python环境中,可以通过`pip install smtplib`和`pip install email`命令进行安装。QQ邮箱作为SMTP服务提供商,需要开启POP3/SMTP服务并获取授权码,此授权码将用于Python脚本登录邮箱。 一、发送普通文本邮件 ```python from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText msg_from = 'your_email@qq.com' passwd = 'your_authorization_code' to = ['recipient_email@qq.com'] msg = MIMEMultipart() content = "这是邮件内容" msg.attach(MIMEText(content, 'plain', 'utf-8')) msg['Subject'] = "这是邮件主题" msg['From'] = msg_from # 使用SSL连接SMTP服务器 s = smtplib.SMTP_SSL('smtp.qq.com', 465) s.login(msg_from, passwd) s.sendmail(msg_from, to, msg.as_string()) print("邮件发送成功") ``` 二、发送携带附件的邮件 ```python from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE from email import encoders msg_from = 'your_email@qq.com' passwd = 'your_authorization_code' to = ['recipient_email@qq.com'] msg = MIMEMultipart() content = "这是邮件内容" msg.attach(MIMEText(content, 'plain', 'utf-8')) # 添加附件 with open('file_name.xlsx', 'rb') as f: part = MIMEBase('application', 'octet-stream') part.set_payload(f.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="file_name.xlsx"') msg.attach(part) msg['Subject'] = "这是带有附件的邮件主题" msg['From'] = msg_from s = smtplib.SMTP_SSL('smtp.qq.com', 465) s.login(msg_from, passwd) s.sendmail(msg_from, to, msg.as_string()) print("邮件发送成功") ``` 三、发送携带图片的附件 发送图片附件与发送附件类似,但需要将图片类型设置为`image/jpeg`或`image/png`等,具体取决于图片的格式。 ```python from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.utils import COMMASPACE from email import encoders msg_from = 'your_email@qq.com' passwd = 'your_authorization_code' to = ['recipient_email@qq.com'] msg = MIMEMultipart() content = "这是邮件内容" msg.attach(MIMEText(content, 'plain', 'utf-8')) # 添加图片附件 with open('image.jpg', 'rb') as f: img = MIMEImage(f.read(), _subtype='jpg') img.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img) msg['Subject'] = "这是带有图片附件的邮件主题" msg['From'] = msg_from s = smtplib.SMTP_SSL('smtp.qq.com', 465) s.login(msg_from, passwd) s.sendmail(msg_from, to, msg.as_string()) print("邮件发送成功") ``` 以上代码示例展示了如何在Python中使用QQ邮箱发送不同类型的邮件。在实际应用中,根据需求可以进一步定制邮件内容,例如添加收件人列表、设置抄送和密送、自定义邮件头等。同时,确保在发送邮件前正确配置QQ邮箱的SMTP设置,并安全保管好授权码,避免泄露。