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

Python中使用MIMEApplication()实现音频文件作为邮件附件的发送

发布时间:2023-12-24 23:41:42

使用Python中的MIMEApplication()可以方便地将音频文件作为邮件附件进行发送。下面是一个使用例子,该例子将一个音频文件作为附件并发送邮件。

首先,我们需要导入必要的库和模块:

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

接下来,我们需要设置邮件发送者、接收者和邮件内容:

sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = '邮件主题'
body = '邮件正文'

然后,我们需要创建一个MIMEMultipart对象,用来存储邮件内容和附件:

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject

接着,我们需要将邮件内容添加到MIMEMultipart对象中:

msg.attach(MIMEText(body, 'plain'))

然后,我们需要读取音频文件,并创建一个MIMEApplication对象来表示附件:

audio_file = 'audio.wav'
with open(audio_file, 'rb') as f:
    attachment = MIMEApplication(f.read(), _subtype='wav')

注意,这里的_subtype参数指定了音频文件的类型,这里用的是.wav文件。

接下来,我们需要设置附件的相关信息,包括文件名和Content-Disposition标头:

attachment.add_header('Content-Disposition', 'attachment', filename=audio_file)

然后,我们将附件添加到MIMEMultipart对象中:

msg.attach(attachment)

最后,我们需要使用smtplib库将邮件发送出去:

smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'username'
password = 'password'
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(username, password)
    server.sendmail(sender, receiver, msg.as_string())
    print('邮件发送成功')
except Exception as e:
    print('邮件发送失败:', str(e))
finally:
    server.quit()

完整的代码如下:

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

sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = '邮件主题'
body = '邮件正文'

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject

msg.attach(MIMEText(body, 'plain'))

audio_file = 'audio.wav'
with open(audio_file, 'rb') as f:
    attachment = MIMEApplication(f.read(), _subtype='wav')
    attachment.add_header('Content-Disposition', 'attachment', filename=audio_file)
    msg.attach(attachment)

smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'username'
password = 'password'
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(username, password)
    server.sendmail(sender, receiver, msg.as_string())
    print('邮件发送成功')
except Exception as e:
    print('邮件发送失败:', str(e))
finally:
    server.quit()

以上就是使用Python中的MIMEApplication()实现音频文件作为邮件附件发送的示例代码。您可以根据自己的实际需求进行修改和扩展。