本文以163邮件系统为例,登录之后,点击设置,开启如下设置项。
即可使用代码发送邮件,并携带附件。
开启SMTP
普通邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart# 163邮箱的SMTP服务器地址和端口
smtp_server = "smtp.163.com"
smtp_port = 465# 发送者的163邮箱账号和密码
sender_email = "xxx@163.com"
sender_password = "xxxxxxxxxxxx"# 接收者的邮箱地址
receiver_email = "xxx@outlook.com"# 创建一个MIMEMultipart对象,用于构建邮件内容
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "Test Email"# 邮件正文内容
body = "This is a test email sent from Python using 163 SMTP server."
msg.attach(MIMEText(body, "plain"))# 附件文件路径
attachment_path = "test.pdf"
attachment_filename = "attachment.pdf"# 连接到163邮箱的SMTP服务器
server = smtplib.SMTP_SSL(smtp_server, smtp_port)# 登录到163邮箱
server.login(sender_email, sender_password)# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())# 关闭服务器连接
server.quit()print("Email sent successfully!")
携带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders# 163邮箱的SMTP服务器地址和端口
smtp_server = "smtp.163.com"
smtp_port = 465# 发送者的163邮箱账号和密码
sender_email = "xxx@163.com"
sender_password = "xxxxxxxxxxx"# 接收者的邮箱地址
receiver_email = "xxx@outlook.com"# 创建一个MIMEMultipart对象,用于构建邮件内容
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "Test Email"# 邮件正文内容
body = "This is a test email sent from Python using 163 SMTP server."
msg.attach(MIMEText(body, "plain"))# 附件文件路径
attachment_path = "test.pdf"
attachment_filename = "attachment.pdf"# 读取附件文件内容
with open(attachment_path, "rb") as attachment_file:part = MIMEBase("application", "octet-stream")part.set_payload(attachment_file.read())encoders.encode_base64(part)part.add_header("Content-Disposition",f"attachment; filename={attachment_filename}",)msg.attach(part)# 连接到163邮箱的SMTP服务器
server = smtplib.SMTP_SSL(smtp_server, smtp_port)# 登录到163邮箱
server.login(sender_email, sender_password)# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())# 关闭服务器连接
server.quit()print("Email sent successfully!")