随便去取 发表于 2023-11-6 10:58

xiaomingtt 发表于 2023-11-6 14:05

本帖最后由 xiaomingtt 于 2023-11-6 15:44 编辑

给你完善一下代码。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from email.utils import parseaddr, formataddr
import mimetypes
import os

def send_email(smtp_server, username, password, sender, recipients, subject, content, cc, bcc, port=25, sendername=None, attachments=None):
    def _format_addr(s):
      name, addr = parseaddr(s)
      return formataddr((Header(name, 'utf-8').encode(), addr))
    if not attachments:
      attachments = []
    msg = MIMEMultipart()
    if sendername:
      msg['From'] = _format_addr(sendername + ' <%s>' % sender)
    else:
      msg['From'] = sender
    if isinstance(recipients, str):
      recipients =
    msg['To'] = ",".join(recipients)
    if cc:
      if isinstance(cc, str):
            cc =
      cc_list =
      if cc_list:
            msg['Cc'] = ",".join(cc_list)
            recipients += cc_list
    if bcc:
      if isinstance(bcc, str):
            bcc =
      bcc_list =
      if bcc_list:
            msg['Bcc'] = ",".join(bcc_list)
            recipients += bcc_list
    msg['Subject'] = Header(subject, 'utf-8').encode()
    text_part = MIMEText(content, 'html', 'utf-8')
    msg.attach(text_part)
    for attachment in attachments:
      file_path = attachment["path"]
      if not os.path.isfile(file_path):
            print("附件文件不存在:{}".format(file_path))
            continue
      try:
            with open(file_path, "rb") as f:
                mime_type, encoding = mimetypes.guess_type(file_path)
                if mime_type is None:
                  mime_type = 'application/octet-stream'
                part = MIMEApplication(f.read())
                part.add_header('Content-Disposition', 'attachment', filename=attachment["filename"])
                part.add_header('Content-Type', mime_type)
                msg.attach(part)
      except FileNotFoundError as e:
            print("文件未找到:{}".format(e))
      except Exception as e:
            print("附件读取失败:{}".format(e))
    try:
      if str(port) == "25":
            server = smtplib.SMTP(smtp_server, port)
      else:
            server = smtplib.SMTP_SSL(smtp_server, port)
      server.login(username, password)
      server.sendmail(sender, recipients, msg.as_string())
      server.quit()
      print("邮件发送成功!")
    except Exception as e:
      print("邮件发送失败:{}".format(e))



smtp_server = "smtp.aliyun.com"
username = "abc@aliyun.com"
password = "password"
sender = "abc@aliyun.com"
recipients = "abc@abc.cn"
cc = ["abc@126.com","abc@139.com"]
bcc = ""
subject = "title"
content = "content"
n = "name"
port = 25
attachments = [{"filename":"申请单.xlsx","path":"C:/申请单.xlsx"},
               {"filename": "新课标.docx", "path": "D:/新课标.docx"},
                {"filename": "笨笨狗.pdf", "path": "D:/books/笨笨狗.pdf"}]

send_email(smtp_server, username, password, sender, recipients, subject, content, cc,bcc,port=port, sendername=n, attachments=attachments)

redapple2015 发表于 2023-11-6 12:22

o365可以发吗?我测试不行。

smile1110 发表于 2023-11-6 12:26

666666666666太棒了

poptop 发表于 2023-11-6 13:13

谢谢分享                                 

CarroAro 发表于 2023-11-6 13:19

看起來應該是gpt輔助寫的
代碼中有你的信箱
記得修改一下

John72 发表于 2023-11-6 13:31

大佬6666

xfmiao 发表于 2023-11-6 16:51

马上收藏学习

backaxe 发表于 2023-11-7 08:21

脑子里过一遍也是可以的。

backaxe 发表于 2023-11-7 08:23

本帖最后由 backaxe 于 2023-11-7 08:24 编辑

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# SMTP服务器设置
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_user = 'your_email@gmail.com'# 你的Gmail邮箱地址
smtp_password = 'your_password'   # 你的Gmail密码或应用专用密码

# 邮件发送者和接收者
sender = smtp_user
receiver = 'receiver@example.com'# 收件人的邮箱地址

# 邮件内容
subject = 'Python SMTP Email Test'
body = """
Hello, this is a test email sent from a Python script using SMTP.
"""

# 创建MIME对象
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = subject

# 邮件正文
message.attach(MIMEText(body, 'plain'))

# 发送邮件
try:
    # 连接到SMTP服务器
    with smtplib.SMTP(smtp_server, smtp_port) as server:
      server.ehlo()          # 发送SMTP 'ehlo' 命令
      server.starttls()      # 启动TLS加密
      server.ehlo()          # 再次发送SMTP 'ehlo' 命令
      server.login(smtp_user, smtp_password)
      
      # 发送邮件
      server.sendmail(sender, receiver, message.as_string())
      print("Email sent successfully!")
except smtplib.SMTPException as e:
    print("Error: unable to send email. Error message:")
    print(e)
页: [1] 2
查看完整版本: Python发送Email电子邮件