1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import smtplib from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.header import Header
def send_email(filename, message_type='html'): mail_host = "smtp.xxx.xxx.xxx" mail_user = "name@xxx.xxx.xxx" mail_pass = "xxxxxx" receivers = ['name@xxx.xxx.xxx',]
sender = 'name@xxx.xxx.xxx'
message=filename header=filename subject=filename part = MIMEText(message, message_type, 'utf-8') message = MIMEMultipart()
message['From'] = Header(header, 'utf-8') message['Subject'] = Header(subject, 'utf-8') message.attach(part)
attachment=MIMEApplication(open(filename, 'rb').read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(attachment)
try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") return True except smtplib.SMTPException: print("Error: 无法发送邮件") return False
if __name__ == '__main__': send_email('test.txt')
|