2 import smtplib, email
3 #from and import key word make it possible that use a variable stand for a specified module name
4 from email import encoders
5 from email.header import Header
6 from email.mime.text import MIMEText
7 from email.mime.multipart import MIMEMultipart
8 from email.mime.base import MIMEBase
9 #from key word copy a module variable name to a specified domain
10 from email.utils import parseaddr, formataddr
11
12 #def a function to format email address
13 def _format_addr(s):
14 (name, addr) = parseaddr(s)
15 return formataddr(( \
16 Header(name, ‘utf-8‘).encode(), \
17 addr))
18
19 #get address and other by input
20 #from_addr = input(‘From: ‘)
21 #from_name = input(‘MyName: ‘)
22 #password = input(‘Password: ‘)
23 #to_addr = input(‘To: ‘)
24 #to_name = input(‘FriendName: ‘)
25 #smtp_server = input(‘SMTP server: ‘)
26 #heading = input(‘Heading: ‘)
27 #main_body = input(‘Main body: ‘)
28 from_addr = ‘xxxx@xxxx.com‘
29 from_name = ‘guy‘
30 password = ‘xxxxx‘
31 #hehe, this is my email
32 to_addr = ‘zdyx0379@163.com‘
33 to_name = ‘zhaodan‘
34 smtp_server = ‘smtp.qq.com‘
35 heading = ‘For my friend‘
36 #text email body
37 main_body_text = ‘i miss you, old friend‘
38 #html email body, say hello and show a picture
39 main_body_html = ‘<html>‘+\
40 ‘<body>‘+\
41 ‘<h1>hello, friend</h1>‘+\
42 ‘<p><img src="cid:0"></p>‘+\
43 ‘</body>‘+\
44 ‘</html>‘
45 from_attr = from_name + ‘ < ‘ + from_addr + ‘ > ‘
46 to_attr = to_name + ‘ < ‘ + to_addr + ‘ > ‘
47
48 #email.mime.multipart can include accessory
49 #email.mime.text only support text, we can add email.mime.text to email.mime.multipart by attach method
50 msg = MIMEMultipart(‘alternative‘)
51 #msg.attach(MIMEText(main_body, ‘plain‘, ‘utf-8‘))
52 msg.attach(MIMEText(main_body_html, ‘html‘, ‘utf-8‘))
53 #email to be send is a list, here
54 msg[‘From‘] = _format_addr(from_attr)
55 msg[‘To‘] = _format_addr(to_attr)
56 msg[‘Subject‘] = Header(heading, ‘utf-8‘).encode()
57 with open(‘E:\\1.jpg‘, ‘rb‘) as f:
58 mime = MIMEBase(‘image‘, ‘jpg‘, filename = ‘1.jpg‘)
59 mime.add_header(‘Context-Disposition‘, ‘attachment‘, filename = ‘1.jpg‘)
60 #set cid of html, then can show img in mail body by html refrence to cid:0
61 mime.add_header(‘Content-ID‘, ‘<0>‘)
62 mime.add_header(‘X-Attachment-ID‘, ‘0‘)
63 #read file and attach file context to mime
64 mime.set_payload(f.read())
65 #encode by base64 code
66 encoders.encode_base64(mime)
67 #attach mime to msg as accessory
68 msg.attach(mime)
69
70 #add a text email, just in case reciver can‘t parse html email
71 msg.attach(MIMEText(main_body_text, ‘plain‘, ‘utf-8‘))
72 server = smtplib.SMTP(smtp_server, 25)
73 server.starttls()
74 server.set_debuglevel(1)
75 server.connect(smtp_server, 25)
76 server.helo()
77 server.ehlo()
78 server.login(from_addr, password)
79 server.sendmail(from_addr, [to_addr], msg.as_string())
80 server.quit()
81 #end