使用Python编写程序,将音频文件添加为电子邮件附件发送。
发布时间:2024-01-16 17:33:29
下面是一个使用Python编写的程序,它可以将音频文件作为电子邮件附件发送出去。这里使用的是smtplib库来发送电子邮件,以及email库来创建邮件内容和附件。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_email(sender_email, sender_password, receiver_email, subject, message, attachment_path):
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(message, 'plain'))
# 打开音频文件并创建附件
attachment = open(attachment_path, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= " + attachment_path)
# 将附件添加到邮件对象中
msg.attach(part)
# 使用SMTP进行邮件发送
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()
# 示例代码
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "receiver_email@gmail.com"
subject = "Example Email"
message = "This is a test email with an audio attachment."
attachment_path = "path_to_audio_file.mp3"
send_email(sender_email, sender_password, receiver_email, subject, message, attachment_path)
请确保将程序中的your_email@gmail.com和your_password替换为发送者的有效邮箱地址和密码,并将receiver_email@gmail.com替换为接收者的邮箱地址。同时,将path_to_audio_file.mp3替换为要发送的音频文件的实际路径。
此程序使用了Gmail作为发件人电子邮件服务,如果你使用其他邮件服务提供商,需要相应修改SMTP服务器的主机名和端口号。
这个程序会创建一个带有音频附件的电子邮件,然后使用SMTP通过发件人电子邮件服务发送出去。接收者将能够收到这个包含音频文件的邮件附件。
