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 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #!/usr/bin/python3
import smtplib from email.header import Header from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart
mail_host = "smtp.chorder.net" mail_port = 994 mail_user = "[email protected]" mail_pass = "password"
sender_name = "Example" sender_account = '[email protected]' receivers = ['[email protected]'] receiver_name = "Somebody"
subject = 'Mail Subject' mail_msg = ''' <h1>This is a test main</h1> <p>Some text</p> <h2>Image</h2> <p><img src="cid:image1"></p> '''
# add image attachment fp = open('test.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header(sender_name, 'utf-8') msgRoot['To'] = Header(receiver_name, 'utf-8') msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative') msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
msgRoot.attach(msgAlternative) msgRoot.attach(msgImage)
try: smtpObj = smtplib.SMTP_SSL( mail_host, mail_port ) #smtpObj.ehlo() #smtpObj.set_debuglevel(1) smtpObj.login( mail_user, mail_pass ) smtpObj.sendmail(sender_account, receivers, msgRoot.as_string()) print ("邮件发送成功") except smtplib.SMTPException: print ("Error: 无法发送邮件")
|