Skip to content

Instantly share code, notes, and snippets.

@thesadabc
Last active February 3, 2024 04:47
Show Gist options
  • Save thesadabc/bc85bf4d9df3cb1755b44216be4dc78b to your computer and use it in GitHub Desktop.
Save thesadabc/bc85bf4d9df3cb1755b44216be4dc78b to your computer and use it in GitHub Desktop.
python使用SMTP,发送带附件的邮件代码示例
"""
python使用SMTP,发送带附件的邮件代码示例
无需安装依赖
"""
import os
from smtplib import SMTP
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
# email sender config
EMAIL_FROM_ADDR = "my@hotmail.com"
EMAIL_FROM_PASS = "ppppppp"
EMAIL_SMTP_SERVER = "smtp-mail.outlook.com"
EMAIL_SMTP_SSL = True
EMAIL_SMTP_PORT = 587
def send_email(addrs, subject, content, attas = []):
msg = MIMEMultipart()
msg["From"] = EMAIL_FROM_ADDR
msg["To"] = COMMASPACE.join(addrs)
msg["Date"] = formatdate(localtime=True)
msg["Subject"] = subject
msg.attach(MIMEText(content))
for filepath in attas:
part = MIMEBase("application", "octet-stream")
with open(filepath, "rb") as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition",
"attachment; filename={}".format(os.path.basename(filepath)))
msg.attach(part)
with SMTP(EMAIL_SMTP_SERVER, EMAIL_SMTP_PORT) as smtp:
if EMAIL_SMTP_SSL:
smtp.starttls()
smtp.login(EMAIL_FROM_ADDR, EMAIL_FROM_PASS)
smtp.sendmail(EMAIL_FROM_ACC, addrs, msg.as_string())
if __name__ == '__main__':
send_email(["addr1@example.com"], "test SUBJECT", "test CONTENT", ["./Book1.xlsx"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment