吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1760|回复: 14
收起左侧

[Python 原创] Python发送Email电子邮件

  [复制链接]
头像被屏蔽
随便去取 发表于 2023-11-6 10:58
提示: 作者被禁止或删除 内容自动屏蔽

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

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

给你完善一下代码。
[Python] 纯文本查看 复制代码
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 = [recipients]
    msg['To'] = ",".join(recipients)
    if cc:
        if isinstance(cc, str):
            cc = [cc]
        cc_list = [addr for addr in cc if addr not in recipients]
        if cc_list:
            msg['Cc'] = ",".join(cc_list)
            recipients += cc_list
    if bcc:
        if isinstance(bcc, str):
            bcc = [bcc]
        bcc_list = [addr for addr in bcc if addr not in recipients]
        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)

点评

一看就是大腿 太强˙  发表于 2023-11-6 14:14
redapple2015 发表于 2023-11-6 12:22
smile1110 发表于 2023-11-6 12:26
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 编辑

[Python] 纯文本查看 复制代码
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)
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-24 17:34

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表