在Linux系统中,可以用mail命令来发送邮件,但带附件发送时,总是报附件过大的错误。在不知道如何配置Linux邮件的情况下,我选择了用Python来实现发送带附件的邮件。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
mail_host="smtp.exmail.qq.com" #设置服务器
mail_user="#填写用户名" #用户名
mail_pass="#用户名对应的密码" #口令
mail_postfix="#发件箱的后缀" #发件箱的后缀
#定义发送邮件的收件人,邮件标题,邮件内容,附件
def send_mail(to_list,sub,content,files):
msg = MIMEMultipart(_subtype='plain',_charset='utf-8')
msg['Subject'] = sub
msg['From'] = mail_user
msg['To'] = ";".join(to_list)
part=MIMEText(content,_subtype='plain',_charset='utf-8')
msg.attach(part)
for file_name in files:
part = MIMEApplication(open(file_name,'rb').read())
part.add_header('Content-Disposition', 'p_w_upload', filename=file_name)
msg.attach(part)
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(mail_user, to_list, msg.as_string())
server.close()
return True
mailto_list=['收件人1','收件人2']
files=['file_name',......]
send_mail(mailto_list,"邮件标题","邮件正文",files)