欢迎访问宙启技术站
智能推送

使用email.mime.audio模块在Python中创建和发送音频邮件的示例

发布时间:2023-12-22 20:53:45

要使用email.mime.audio模块在Python中创建和发送音频邮件,我们首先需要导入必要的模块和类。以下是一个示例代码,其中包括创建音频邮件、添加音频附件和发送邮件的过程。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.audio import MIMEAudio
from email.mime.text import MIMEText
from email.utils import COMMASPACE


# 填写发送方和接收方的邮箱地址
sender = "sender@example.com"
receivers = ["receiver1@example.com", "receiver2@example.com"]

# 创建一个多部分消息对象
msg = MIMEMultipart()

# 填写邮件的发送者,接收者和主题
msg["From"] = sender
msg["To"] = COMMASPACE.join(receivers)
msg["Subject"] = "音频邮件示例"

# 添加邮件正文
msg.attach(MIMEText("这是一封包含音频附件的示例邮件。"))

# 打开音频文件,并将其作为附件添加到邮件中
audio_file = "path/to/audio.mp3"
with open(audio_file, "rb") as f:
    audio_data = f.read()

audio_part = MIMEAudio(audio_data)
audio_part.add_header("Content-Disposition", "attachment; filename=audio.mp3")
msg.attach(audio_part)

# 发送邮件
smtp_server = "smtp.example.com"
smtp_username = "username"
smtp_password = "password"

try:
    smtp = smtplib.SMTP(smtp_server)
    smtp.login(smtp_username, smtp_password)
    smtp.sendmail(sender, receivers, msg.as_string())
    smtp.quit()
    print("邮件发送成功")
except Exception as e:
    print("邮件发送失败:", str(e))

请注意,上面的代码中使用的音频文件路径应该根据实际情况进行更改。还需要替换邮件服务器的地址、用户名和密码。

此代码创建一个MIMEMultipart对象,该对象表示一个包含音频附件的邮件。它将音频文件读取为二进制数据,并使用MIMEAudio类将其添加为附件。然后使用smtplib库中的SMTP类将邮件发送到接收方。

通过更改邮件内容、收件人列表和附件路径,您可以根据自己的需求自定义示例代码。