Let's establish the session with Google server:
session = smtplib.SMTP('smtp.gmail.com',587)
Opps:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'smtplib' is not defined
Need to import module before start:
import smtplib
Let's establish again the session:
session = smtplib.SMTP('smtp.gmail.com',587)
What is inside in this session variable:
print session
<smtplib.SMTP instance at 0x02F0A788>
Check some service availability:
session.ehlo()
(250, 'smtp.gmail.com at your service, [87.110.183.173]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
Check if seccure connection is available:
session.starttls()
(220, '2.0.0 Ready to start TLS')
Do the eclo again:
session.ehlo()
(250, 'smtp.gmail.com at your service, [87.110.183.173]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
Authorize with credentials:
session.login('catonrug.secondo@gmail.com', 'QnMgPRKjvb42GNmZ')
(235, '2.7.0 Accepted')
Now we will prepare the message. Let's print existing variable:
print msg
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'msg' is not defined
Looks like there is no template for msg. Let's start with email body:
msg = MIMEText('body', 'plain', 'utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'MIMEText' is not defined
MIMEText module must be imported:
from email.mime.text import MIMEText
prepait again the body:
msg = MIMEText('body', 'plain', 'utf-8')
Check out how the body has been changed:
print msg
From nobody Fri Jun 22 14:41:38 2018
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Ym9keQ==
msg['Subject'] = Header('subject', 'utf-8')
from email.Header import Header
msg['Subject'] = Header('subject', 'utf-8')
print msg
msg['From'] = Header('catonrug@gmail.com', 'utf-8')
print msg
msg['To'] = 'aigars@gmail.com'
print msg
msg['Date'] = formatdate()
from email.Utils import formatdate
msg['Date'] = formatdate()
print msg
session.sendmail('catonrug@gmail.com', 'aigars@gmail.com', msg.as_string())
No comments:
Post a Comment