Guest User

Untitled

a guest
Jan 9th, 2018
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.78 KB | None | 0 0
  1. raise SMTPException("SMTP AUTH extension not supported by server.")
  2. smtplib.SMTPException: SMTP AUTH extension not supported by server.
  3.  
  4. pip install --upgrade google-api-python-client
  5.  
  6. import httplib2
  7. import os
  8. import oauth2client
  9. from oauth2client import client, tools
  10. import base64
  11. from email.mime.multipart import MIMEMultipart
  12. from email.mime.text import MIMEText
  13. from apiclient import errors, discovery
  14. import mimetypes
  15. from email.mime.image import MIMEImage
  16. from email.mime.audio import MIMEAudio
  17. from email.mime.base import MIMEBase
  18.  
  19. SCOPES = 'https://www.googleapis.com/auth/gmail.send'
  20. CLIENT_SECRET_FILE = 'client_secret.json'
  21. APPLICATION_NAME = 'Gmail API Python Send Email'
  22.  
  23. def get_credentials():
  24. home_dir = os.path.expanduser('~')
  25. credential_dir = os.path.join(home_dir, '.credentials')
  26. if not os.path.exists(credential_dir):
  27. os.makedirs(credential_dir)
  28. credential_path = os.path.join(credential_dir,
  29. 'gmail-python-email-send.json')
  30. store = oauth2client.file.Storage(credential_path)
  31. credentials = store.get()
  32. if not credentials or credentials.invalid:
  33. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  34. flow.user_agent = APPLICATION_NAME
  35. credentials = tools.run_flow(flow, store)
  36. print('Storing credentials to ' + credential_path)
  37. return credentials
  38.  
  39. def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None):
  40. credentials = get_credentials()
  41. http = credentials.authorize(httplib2.Http())
  42. service = discovery.build('gmail', 'v1', http=http)
  43. if attachmentFile:
  44. message1 = createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
  45. else:
  46. message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain)
  47. result = SendMessageInternal(service, "me", message1)
  48. return result
  49.  
  50. def SendMessageInternal(service, user_id, message):
  51. try:
  52. message = (service.users().messages().send(userId=user_id, body=message).execute())
  53. print('Message Id: %s' % message['id'])
  54. return message
  55. except errors.HttpError as error:
  56. print('An error occurred: %s' % error)
  57. return "Error"
  58. return "OK"
  59.  
  60. def CreateMessageHtml(sender, to, subject, msgHtml, msgPlain):
  61. msg = MIMEMultipart('alternative')
  62. msg['Subject'] = subject
  63. msg['From'] = sender
  64. msg['To'] = to
  65. msg.attach(MIMEText(msgPlain, 'plain'))
  66. msg.attach(MIMEText(msgHtml, 'html'))
  67. return {'raw': base64.urlsafe_b64encode(msg.as_string())}
  68.  
  69. def createMessageWithAttachment(
  70. sender, to, subject, msgHtml, msgPlain, attachmentFile):
  71. """Create a message for an email.
  72.  
  73. Args:
  74. sender: Email address of the sender.
  75. to: Email address of the receiver.
  76. subject: The subject of the email message.
  77. msgHtml: Html message to be sent
  78. msgPlain: Alternative plain text message for older email clients
  79. attachmentFile: The path to the file to be attached.
  80.  
  81. Returns:
  82. An object containing a base64url encoded email object.
  83. """
  84. message = MIMEMultipart('mixed')
  85. message['to'] = to
  86. message['from'] = sender
  87. message['subject'] = subject
  88.  
  89. messageA = MIMEMultipart('alternative')
  90. messageR = MIMEMultipart('related')
  91.  
  92. messageR.attach(MIMEText(msgHtml, 'html'))
  93. messageA.attach(MIMEText(msgPlain, 'plain'))
  94. messageA.attach(messageR)
  95.  
  96. message.attach(messageA)
  97.  
  98. print("create_message_with_attachment: file: %s" % attachmentFile)
  99. content_type, encoding = mimetypes.guess_type(attachmentFile)
  100.  
  101. if content_type is None or encoding is not None:
  102. content_type = 'application/octet-stream'
  103. main_type, sub_type = content_type.split('/', 1)
  104. if main_type == 'text':
  105. fp = open(attachmentFile, 'rb')
  106. msg = MIMEText(fp.read(), _subtype=sub_type)
  107. fp.close()
  108. elif main_type == 'image':
  109. fp = open(attachmentFile, 'rb')
  110. msg = MIMEImage(fp.read(), _subtype=sub_type)
  111. fp.close()
  112. elif main_type == 'audio':
  113. fp = open(attachmentFile, 'rb')
  114. msg = MIMEAudio(fp.read(), _subtype=sub_type)
  115. fp.close()
  116. else:
  117. fp = open(attachmentFile, 'rb')
  118. msg = MIMEBase(main_type, sub_type)
  119. msg.set_payload(fp.read())
  120. fp.close()
  121. filename = os.path.basename(attachmentFile)
  122. msg.add_header('Content-Disposition', 'attachment', filename=filename)
  123. message.attach(msg)
  124.  
  125. return {'raw': base64.urlsafe_b64encode(message.as_string())}
  126.  
  127.  
  128. def main():
  129. to = "to@address.com"
  130. sender = "from@address.com"
  131. subject = "subject"
  132. msgHtml = "Hi<br/>Html Email"
  133. msgPlain = "HinPlain Email"
  134. SendMessage(sender, to, subject, msgHtml, msgPlain)
  135. # Send message with attachment:
  136. SendMessage(sender, to, subject, msgHtml, msgPlain, '/path/to/file.pdf')
  137.  
  138. if __name__ == '__main__':
  139. main()
  140.  
  141. ~/.credentials/gmail-python-email-send.json
  142.  
  143. import httplib2
  144. import os
  145. import oauth2client
  146. from oauth2client import client, tools
  147. import base64
  148. from email.mime.multipart import MIMEMultipart
  149. from email.mime.text import MIMEText
  150. from apiclient import errors, discovery
  151.  
  152. SCOPES = 'https://www.googleapis.com/auth/gmail.send'
  153. CLIENT_SECRET_FILE = 'client_secret.json'
  154. APPLICATION_NAME = 'Gmail API Python Send Email'
  155.  
  156. def get_credentials():
  157. home_dir = os.path.expanduser('~')
  158. credential_dir = os.path.join(home_dir, '.credentials')
  159. if not os.path.exists(credential_dir):
  160. os.makedirs(credential_dir)
  161. credential_path = os.path.join(credential_dir, 'gmail-python-email-send.json')
  162. store = oauth2client.file.Storage(credential_path)
  163. credentials = store.get()
  164. if not credentials or credentials.invalid:
  165. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  166. flow.user_agent = APPLICATION_NAME
  167. credentials = tools.run_flow(flow, store)
  168. print('Storing credentials to ' + credential_path)
  169. return credentials
  170.  
  171. def SendMessage(sender, to, subject, msgHtml, msgPlain):
  172. credentials = get_credentials()
  173. http = credentials.authorize(httplib2.Http())
  174. service = discovery.build('gmail', 'v1', http=http)
  175. message1 = CreateMessage(sender, to, subject, msgHtml, msgPlain)
  176. SendMessageInternal(service, "me", message1)
  177.  
  178. def SendMessageInternal(service, user_id, message):
  179. try:
  180. message = (service.users().messages().send(userId=user_id, body=message).execute())
  181. print('Message Id: %s' % message['id'])
  182. return message
  183. except errors.HttpError as error:
  184. print('An error occurred: %s' % error)
  185.  
  186. def CreateMessage(sender, to, subject, msgHtml, msgPlain):
  187. msg = MIMEMultipart('alternative')
  188. msg['Subject'] = subject
  189. msg['From'] = sender
  190. msg['To'] = to
  191. msg.attach(MIMEText(msgPlain, 'plain'))
  192. msg.attach(MIMEText(msgHtml, 'html'))
  193. raw = base64.urlsafe_b64encode(msg.as_bytes())
  194. raw = raw.decode()
  195. body = {'raw': raw}
  196. return body
  197.  
  198. def main():
  199. to = "to@address.com"
  200. sender = "from@address.com"
  201. subject = "subject"
  202. msgHtml = "Hi<br/>Html Email"
  203. msgPlain = "HinPlain Email"
  204. SendMessage(sender, to, subject, msgHtml, msgPlain)
  205.  
  206. if __name__ == '__main__':
  207. main()
  208.  
  209. import httplib2
  210. import os
  211. import oauth2client
  212. from oauth2client import client, tools
  213. import base64
  214. from email import encoders
  215.  
  216. #needed for attachment
  217. import smtplib
  218. import mimetypes
  219. from email import encoders
  220. from email.message import Message
  221. from email.mime.audio import MIMEAudio
  222. from email.mime.base import MIMEBase
  223. from email.mime.image import MIMEImage
  224. from email.mime.multipart import MIMEMultipart
  225. from email.mime.text import MIMEText
  226. from email.mime.application import MIMEApplication
  227. #List of all mimetype per extension: http://help.dottoro.com/lapuadlp.php or http://mime.ritey.com/
  228.  
  229. from apiclient import errors, discovery #needed for gmail service
  230.  
  231.  
  232.  
  233.  
  234. ## About credentials
  235. # There are 2 types of "credentials":
  236. # the one created and downloaded from https://console.developers.google.com/apis/ (let's call it the client_id)
  237. # the one that will be created from the downloaded client_id (let's call it credentials, it will be store in C:Usersuser.credentials)
  238.  
  239.  
  240. #Getting the CLIENT_ID
  241. # 1) enable the api you need on https://console.developers.google.com/apis/
  242. # 2) download the .json file (this is the CLIENT_ID)
  243. # 3) save the CLIENT_ID in same folder as your script.py
  244. # 4) update the CLIENT_SECRET_FILE (in the code below) with the CLIENT_ID filename
  245.  
  246.  
  247. #Optional
  248. # If you don't change the permission ("scope"):
  249. #the CLIENT_ID could be deleted after creating the credential (after the first run)
  250.  
  251. # If you need to change the scope:
  252. # you will need the CLIENT_ID each time to create a new credential that contains the new scope.
  253. # Set a new credentials_path for the new credential (because it's another file)
  254. def get_credentials():
  255. # If needed create folder for credential
  256. home_dir = os.path.expanduser('~') #>> C:UsersMe
  257. credential_dir = os.path.join(home_dir, '.credentials') # >>C:UsersMe.credentials (it's a folder)
  258. if not os.path.exists(credential_dir):
  259. os.makedirs(credential_dir) #create folder if doesnt exist
  260. credential_path = os.path.join(credential_dir, 'cred send mail.json')
  261.  
  262. #Store the credential
  263. store = oauth2client.file.Storage(credential_path)
  264. credentials = store.get()
  265.  
  266. if not credentials or credentials.invalid:
  267. CLIENT_SECRET_FILE = 'client_id to send Gmail.json'
  268. APPLICATION_NAME = 'Gmail API Python Send Email'
  269. #The scope URL for read/write access to a user's calendar data
  270.  
  271. SCOPES = 'https://www.googleapis.com/auth/gmail.send'
  272.  
  273. # Create a flow object. (it assists with OAuth 2.0 steps to get user authorization + credentials)
  274. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  275. flow.user_agent = APPLICATION_NAME
  276.  
  277. credentials = tools.run_flow(flow, store)
  278.  
  279. return credentials
  280.  
  281.  
  282.  
  283.  
  284. ## Get creds, prepare message and send it
  285. def create_message_and_send(sender, to, subject, message_text_plain, message_text_html, attached_file):
  286. credentials = get_credentials()
  287.  
  288. # Create an httplib2.Http object to handle our HTTP requests, and authorize it using credentials.authorize()
  289. http = httplib2.Http()
  290.  
  291. # http is the authorized httplib2.Http()
  292. http = credentials.authorize(http) #or: http = credentials.authorize(httplib2.Http())
  293.  
  294. service = discovery.build('gmail', 'v1', http=http)
  295.  
  296. ## without attachment
  297. message_without_attachment = create_message_without_attachment(sender, to, subject, message_text_html, message_text_plain)
  298. send_Message_without_attachement(service, "me", message_without_attachment, message_text_plain)
  299.  
  300.  
  301. ## with attachment
  302. # message_with_attachment = create_Message_with_attachment(sender, to, subject, message_text_plain, message_text_html, attached_file)
  303. # send_Message_with_attachement(service, "me", message_with_attachment, message_text_plain,attached_file)
  304.  
  305. def create_message_without_attachment (sender, to, subject, message_text_html, message_text_plain):
  306. #Create message container
  307. message = MIMEMultipart('alternative') # needed for both plain & HTML (the MIME type is multipart/alternative)
  308. message['Subject'] = subject
  309. message['From'] = sender
  310. message['To'] = to
  311.  
  312. #Create the body of the message (a plain-text and an HTML version)
  313. message.attach(MIMEText(message_text_plain, 'plain'))
  314. message.attach(MIMEText(message_text_html, 'html'))
  315.  
  316. raw_message_no_attachment = base64.urlsafe_b64encode(message.as_bytes())
  317. raw_message_no_attachment = raw_message_no_attachment.decode()
  318. body = {'raw': raw_message_no_attachment}
  319. return body
  320.  
  321.  
  322.  
  323. def create_Message_with_attachment(sender, to, subject, message_text_plain, message_text_html, attached_file):
  324. """Create a message for an email.
  325.  
  326. message_text: The text of the email message.
  327. attached_file: The path to the file to be attached.
  328.  
  329. Returns:
  330. An object containing a base64url encoded email object.
  331. """
  332.  
  333. ##An email is composed of 3 part :
  334. #part 1: create the message container using a dictionary { to, from, subject }
  335. #part 2: attach the message_text with .attach() (could be plain and/or html)
  336. #part 3(optional): an attachment added with .attach()
  337.  
  338. ## Part 1
  339. message = MIMEMultipart() #when alternative: no attach, but only plain_text
  340. message['to'] = to
  341. message['from'] = sender
  342. message['subject'] = subject
  343.  
  344. ## Part 2 (the message_text)
  345. # The order count: the first (html) will be use for email, the second will be attached (unless you comment it)
  346. message.attach(MIMEText(message_text_html, 'html'))
  347. message.attach(MIMEText(message_text_plain, 'plain'))
  348.  
  349. ## Part 3 (attachement)
  350. # # to attach a text file you containing "test" you would do:
  351. # # message.attach(MIMEText("test", 'plain'))
  352.  
  353. #-----About MimeTypes:
  354. # It tells gmail which application it should use to read the attachement (it acts like an extension for windows).
  355. # If you dont provide it, you just wont be able to read the attachement (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension).
  356.  
  357. #-----3.1 get MimeType of attachment
  358. #option 1: if you want to attach the same file just specify it’s mime types
  359.  
  360. #option 2: if you want to attach any file use mimetypes.guess_type(attached_file)
  361.  
  362. my_mimetype, encoding = mimetypes.guess_type(attached_file)
  363.  
  364. # If the extension is not recognized it will return: (None, None)
  365. # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
  366. #for unrecognized extension it set my_mimetypes to 'application/octet-stream' (so it won't return None again).
  367. if my_mimetype is None or encoding is not None:
  368. my_mimetype = 'application/octet-stream'
  369.  
  370.  
  371. main_type, sub_type = my_mimetype.split('/', 1)# split only at the first '/'
  372. # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3
  373.  
  374. #-----3.2 creating the attachement
  375. #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach
  376.  
  377. #option 1: use MIMEBase for all my_mimetype (cf below) - this is the easiest one to understand
  378. #option 2: use the specific MIME (ex for .mp3 = MIMEAudio) - it's a shorcut version of MIMEBase
  379.  
  380. #this part is used to tell how the file should be read and stored (r, or rb, etc.)
  381. if main_type == 'text':
  382. print("text")
  383. temp = open(attached_file, 'r') # 'rb' will send this error: 'bytes' object has no attribute 'encode'
  384. attachement = MIMEText(temp.read(), _subtype=sub_type)
  385. temp.close()
  386.  
  387. elif main_type == 'image':
  388. print("image")
  389. temp = open(attached_file, 'rb')
  390. attachement = MIMEImage(temp.read(), _subtype=sub_type)
  391. temp.close()
  392.  
  393. elif main_type == 'audio':
  394. print("audio")
  395. temp = open(attached_file, 'rb')
  396. attachement = MIMEAudio(temp.read(), _subtype=sub_type)
  397. temp.close()
  398.  
  399. elif main_type == 'application' and sub_type == 'pdf':
  400. temp = open(attached_file, 'rb')
  401. attachement = MIMEApplication(temp.read(), _subtype=sub_type)
  402. temp.close()
  403.  
  404. else:
  405. attachement = MIMEBase(main_type, sub_type)
  406. temp = open(attached_file, 'rb')
  407. attachement.set_payload(temp.read())
  408. temp.close()
  409.  
  410. #-----3.3 encode the attachment, add a header and attach it to the message
  411. encoders.encode_base64(attachement) #https://docs.python.org/3/library/email-examples.html
  412. filename = os.path.basename(attached_file)
  413. attachement.add_header('Content-Disposition', 'attachment', filename=filename) # name preview in email
  414. message.attach(attachement)
  415.  
  416.  
  417. ## Part 4 encode the message (the message should be in bytes)
  418. message_as_bytes = message.as_bytes() # the message should converted from string to bytes.
  419. message_as_base64 = base64.urlsafe_b64encode(message_as_bytes) #encode in base64 (printable letters coding)
  420. raw = message_as_base64.decode() # need to JSON serializable (no idea what does it means)
  421. return {'raw': raw}
  422.  
  423.  
  424.  
  425. def send_Message_without_attachement(service, user_id, body, message_text_plain):
  426. try:
  427. message_sent = (service.users().messages().send(userId=user_id, body=body).execute())
  428. message_id = message_sent['id']
  429. # print(attached_file)
  430. print (f'Message sent (without attachment) nn Message Id: {message_id}nn Message:nn {message_text_plain}')
  431. # return body
  432. except errors.HttpError as error:
  433. print (f'An error occurred: {error}')
  434.  
  435.  
  436.  
  437.  
  438. def send_Message_with_attachement(service, user_id, message_with_attachment, message_text_plain, attached_file):
  439. """Send an email message.
  440.  
  441. Args:
  442. service: Authorized Gmail API service instance.
  443. user_id: User's email address. The special value "me" can be used to indicate the authenticated user.
  444. message: Message to be sent.
  445.  
  446. Returns:
  447. Sent Message.
  448. """
  449. try:
  450. message_sent = (service.users().messages().send(userId=user_id, body=message_with_attachment).execute())
  451. message_id = message_sent['id']
  452. # print(attached_file)
  453.  
  454. # return message_sent
  455. except errors.HttpError as error:
  456. print (f'An error occurred: {error}')
  457.  
  458.  
  459. def main():
  460. to = "youremail@gmail.com"
  461. sender = "myemail@gmail.com"
  462. subject = "subject test1"
  463. message_text_html = r'Hi<br/>Html <b>hello</b>'
  464. message_text_plain = "HinPlain Email"
  465. attached_file = r'C:UsersMeDesktopaudio.m4a'
  466. create_message_and_send(sender, to, subject, message_text_plain, message_text_html, attached_file)
  467.  
  468.  
  469. if __name__ == '__main__':
  470. main()
  471.  
  472. print (f'An error occurred: {error}')
  473.  
  474. print ('An error occurred: {error}')
Add Comment
Please, Sign In to add comment