· 10 years ago · Jan 09, 2016, 07:54 PM
1import smtplib
2from email.mime.multipart import MIMEMultipart
3from email.mime.text import MIMEText
4from email.mime.application import MIMEApplication
5from smtplib import SMTPAuthenticationError
6
7username = 'x' # Email Address from the email you want to send an email
8password = 'x' # Password
9
10"""
11SMTP Server Information
121. Gmail.com: smtp.gmail.com:587
132. Outlook.com: smtp-mail.outlook.com:587
143. Office 365: outlook.office365.com
154. Free: smtp.free.fr : 25
16Please verify your SMTP settings info.
17"""
18
19# Create the body of the message (a HTML version for formatting).
20html = """Test d'envoit de message automatique."""
21
22
23# Function that send email.
24def send_mail(username, password, from_addr, to_addrs, msg):
25 server = smtplib.SMTP('smtp-mail.outlook.com', '25')
26 server.ehlo()
27 server.starttls()
28 server.ehlo()
29 server.login(username, password)
30 server.sendmail(from_addr, to_addrs, msg.as_string())
31 server.quit()
32
33# Read email list txt
34"""email_list = [line.strip() for line in open('email.txt')]
35
36for to_addrs in email_list:
37 msg = MIMEMultipart()
38
39 msg['Subject'] = "Hello How are you ?"
40 msg['From'] = from_addr
41 msg['To'] = to_addrs
42
43 # Attach HTML to the email
44 body = MIMEText(html, 'html')
45 msg.attach(body)
46
47 # Attach Cover Letter to the email
48 cover_letter = MIMEApplication(open("file1.pdf", "rb").read())
49 cover_letter.add_header('Content-Disposition', 'attachment', filename="file1.pdf")
50 msg.attach(cover_letter)
51
52 # Attach Resume to the email
53 cover_letter = MIMEApplication(open("file2.pdf", "rb").read())
54 cover_letter.add_header('Content-Disposition', 'attachment', filename="file2.pdf")
55 msg.attach(cover_letter)"""
56
57try:
58 send_mail(username, password, "x", "x", html)
59 print("Email successfully sent to", to_addrs)
60except SMTPAuthenticationError:
61 print('SMTPAuthenticationError')
62 print("Email not sent to", to_addrs)
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81~$ x
82Traceback (most recent call last):
83 File x, line 60, in <module>
84 send_mail(username, password, x, x, html)
85 File x, line 27, in send_mail
86 server = smtplib.SMTP('smtp.free.fr', '25')
87 File "/usr/lib/python3.4/smtplib.py", line 242, in __init__
88 (code, msg) = self.connect(host, port)
89 File "/usr/lib/python3.4/smtplib.py", line 321, in connect
90 self.sock = self._get_socket(host, port, self.timeout)
91 File "/usr/lib/python3.4/smtplib.py", line 292, in _get_socket
92 self.source_address)
93 File "/usr/lib/python3.4/socket.py", line 509, in create_connection
94 raise err
95 File "/usr/lib/python3.4/socket.py", line 500, in create_connection
96 sock.connect(sa)
97OSError: [Errno 101] Network is unreachable