{"id":5497,"date":"2020-04-12T19:17:46","date_gmt":"2020-04-12T17:17:46","guid":{"rendered":"https:\/\/pythonprogramming.altervista.org\/?p=5497"},"modified":"2020-04-12T19:23:42","modified_gmt":"2020-04-12T17:23:42","slug":"send-a-pdf-with-an-email-with-python","status":"publish","type":"post","link":"https:\/\/pythonprogramming.altervista.org\/send-a-pdf-with-an-email-with-python\/","title":{"rendered":"Send a pdf with an email with python"},"content":{"rendered":"<p>To send an attachment in an email you need to (take from <a href=\"https:\/\/www.tutorialspoint.com\/send-mail-with-attachment-from-your-gmail-account-using-python\">here<\/a>):<\/p>\n<ul class=\"list\">\n<li>Create MIME<\/li>\n<li>Add sender, receiver address into the MIME<\/li>\n<li>Add the mail title into the MIME<\/li>\n<li>Attach the body into the MIME<\/li>\n<li>Open the file as binary mode, which is going to be attached with the mail<\/li>\n<li>Read the byte stream and encode the attachment using base64 encoding scheme.<\/li>\n<li>Add header for the attachments<\/li>\n<li>Start the SMTP session with valid port number with proper security features.<\/li>\n<li>Login to the system.<\/li>\n<li>Send mail and exit<\/li>\n<\/ul>\n<h2>The modules<\/h2>\n<p>These are the modules needed<\/p>\n<pre class=\"lang:default decode:true\">import smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.base import MIMEBase\r\nfrom email import encoders<\/pre>\n<h2>What&#8217;s a MIME?<\/h2>\n<p>The MIME\u00a0 (Multipurpose Internet\u00a0<em>Mail<\/em> Extensions) is an Internet standard that <strong>extends<\/strong> the format of <strong><em>email<\/em>\u00a0messages<\/strong> to support text in character sets other than ASCII, as well as <strong>attachments<\/strong> of audio, video, images, and application programs.<\/p>\n<h2>The body of the email<\/h2>\n<pre class=\"lang:default decode:true\">body = '''Hello,\r\nThis is the body of the email\r\nsicerely yours\r\nG.G.\r\n'''<\/pre>\n<h2>Sender and receiver<\/h2>\n<pre class=\"lang:default decode:true\">sender = 'sender@gmail.com'\r\npassword = 'xxxxxxxx'\r\nreceiver = 'receiver@gmail.com'<\/pre>\n<h2>Let&#8217;s setup the MIME<\/h2>\n<pre class=\"lang:default decode:true \">#Setup the MIME\r\nmessage = MIMEMultipart()\r\nmessage['From'] = sender\r\nmessage['To'] = receiver\r\nmessage['Subject'] = 'This email has an attacment, a pdf file'<\/pre>\n<h2>We attach the body (MIMEText)<\/h2>\n<pre class=\"lang:default decode:true\">message.attach(MIMEText(body, 'plain'))<\/pre>\n<h2>Attach the pdf<\/h2>\n<pre class=\"lang:default decode:true\">pdfname = 'TP_python_prev.pdf'\r\n\r\n# open the file in bynary\r\nbinary_pdf = open(pdfname, 'rb')\r\n\r\npayload = MIMEBase('application', 'octate-stream', Name=pdfname)\r\npayload.set_payload((binary_pdf).read())\r\n\r\n# enconding the binary into base64\r\nencoders.encode_base64(payload)\r\n\r\n# add header with pdf name\r\npayload.add_header('Content-Decomposition', 'attachment', filename=pdfname)\r\nmessage.attach(payload)<\/pre>\n<h2>Create Smtp session to send email<\/h2>\n<pre class=\"lang:default decode:true \">#use gmail with port\r\nsession = smtplib.SMTP('smtp.gmail.com', 587)\r\n\r\n#enable security\r\nsession.starttls()\r\n\r\n#login with mail_id and password\r\nsession.login(sender, password)\r\n\r\ntext = message.as_string()\r\nsession.sendmail(sender, receiver, text)\r\nsession.quit()\r\nprint('Mail Sent')<\/pre>\n<h2>The whole code<\/h2>\n<pre class=\"lang:default decode:true \">import smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.base import MIMEBase\r\nfrom email import encoders\r\n\r\nbody = '''Hello,\r\nThis is the body of the email\r\nsicerely yours\r\nG.G.\r\n'''\r\n# put your email here\r\nsender = 'sender@gmail.com'\r\n# get the password in the gmail (manage your google account, click on the avatar on the right)\r\n# then go to security (right) and app password (center)\r\n# insert the password and then choose mail and this computer and then generate\r\n# copy the password generated here\r\npassword = 'xxxxxxxxxxxxxxxxxxxxxxxx'\r\n# put the email of the receiver here\r\nreceiver = 'receiver@gmail.com'\r\n\r\n#Setup the MIME\r\nmessage = MIMEMultipart()\r\nmessage['From'] = sender\r\nmessage['To'] = receiver\r\nmessage['Subject'] = 'This email has an attacment, a pdf file'\r\n\r\nmessage.attach(MIMEText(body, 'plain'))\r\n\r\npdfname = 'es_full.pdf'\r\n\r\n# open the file in bynary\r\nbinary_pdf = open(pdfname, 'rb')\r\n\r\npayload = MIMEBase('application', 'octate-stream', Name=pdfname)\r\n# payload = MIMEBase('application', 'pdf', Name=pdfname)\r\npayload.set_payload((binary_pdf).read())\r\n\r\n# enconding the binary into base64\r\nencoders.encode_base64(payload)\r\n\r\n# add header with pdf name\r\npayload.add_header('Content-Decomposition', 'attachment', filename=pdfname)\r\nmessage.attach(payload)\r\n\r\n#use gmail with port\r\nsession = smtplib.SMTP('smtp.gmail.com', 587)\r\n\r\n#enable security\r\nsession.starttls()\r\n\r\n#login with mail_id and password\r\nsession.login(sender, password)\r\n\r\ntext = message.as_string()\r\nsession.sendmail(sender, receiver, text)\r\nsession.quit()\r\nprint('Mail Sent')<\/pre>\n<!-- se vuoi mettere un testo scorrevole\r\n[hoops name=\"typeWriterGen\"]\r\n\r\npoi metti un id diverso per ogni testo nella stessa pagina\r\n\r\n<div id=\"div01\">\r\n<script>\r\n\r\ntypeWriterGen(\"div01\",\"Esempio di testo scorrevole\");\r\n<\/script>\r\n\r\n-->\r\n<style>\r\n.avatar {\r\n  vertical-align: middle;\r\n  width: 100px;\r\n  height: 100px;\r\n  border-radius: 50%;\r\n}\r\n<\/style>\r\n\r\n<hr>\r\n\r\n<!-- NEWSLETTER LINK -->\r\n<a href=\"https:\/\/docs.google.com\/forms\/d\/e\/1FAIpQLSf7TniIPCWHDzCSGh2dYZaCwDvi9yLKS5ovFdKuK1sdfOvwEg\/viewform\">\r\n<img decoding=\"async\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2023\/08\/image-13.png\" class=\"avatar\">\r\nSubscribe to the <b>newsletter<\/b> for updates<\/a><br>\r\n\r\n<!-- TKINTER TEMPLATE LINK -->\r\n<a href=\"https:\/\/pythonprogramming.altervista.org\/tkinter-templates\/\">\r\n<img decoding=\"async\" src=\"https:\/\/i0.wp.com\/pythonprogramming.altervista.org\/wp-content\/uploads\/2023\/07\/image-26.png\" class=\"avatar\">\r\nTkinter templates<\/a><br>\r\n\r\n<!-- MY AVATAR PUT A LINK TO YOUTUBE CHANNEL-->\r\n<iframe loading=\"lazy\" frameborder=\"0\" src=\"https:\/\/itch.io\/embed\/711828\" width=\"552\" height=\"167\"><a href=\"https:\/\/pythonprogrammi.itch.io\/pysnake\">PySnake by PythonProgrammi<\/a><\/iframe>\r\n<br>\r\n<style>\r\n.avatar {\r\n  vertical-align: middle;\r\n  width: 100px;\r\n  height: 100px;\r\n  border-radius: 50%;\r\n}\r\n<\/style>\r\n\r\n\r\n<a href=\"https:\/\/www.youtube.com\/channel\/UCzbxq5e9gLiY-je2-br1rvg\">\r\n\t<img decoding=\"async\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2020\/10\/avatar64x64.png\" alt=\"Avatar\" class=\"avatar\">\r\n\t My youtube channel<\/a><br>\r\n\r\n<br>\r\n\r\nTwitter: <a href=\"https:\/\/twitter.com\/pythonprogrammi\">@pythonprogrammi - python_pygame<\/a>\r\n<h3>Claude's Games<\/h3>\r\n<p><a href=\"https:\/\/pythonprogramming.altervista.org\/random-daily-game-1-arkanoid\/\">Arkanoid<\/a><br>\r\n<a href=\"https:\/\/pythonprogramming.altervista.org\/platform-2d-with-pygame-made-with-claude\/\">Platform 2d<\/a><\/p> <!-- videogames made with claude -->\r\n<a href=\"https:\/\/pythonprogramming.altervista.org\/artifacts-games-day-1-memory-game\/\">1. Memory game<\/a>\r\n<h4>Videos<\/h4>\r\n<a href=\"https:\/\/youtu.be\/ciLjWWw5pLY\">Speech recognition game<\/a>\r\n<h3>Pygame's Platform Game<\/h3>\r\n\r\n<a href=\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-5-sounds-and-mixer\/\"><img decoding=\"async\" src=\"https:\/\/i1.wp.com\/pythonprogramming.altervista.org\/wp-content\/uploads\/2020\/01\/climbercover.png?w=557&ssl=1\"\/ width=\"50%\"><\/a>\r\n<script>\r\nvar title = \"Platform Pygame\";\r\n\t\tvar links = [\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-animation-of-a-sprite-v-1-3\/\",\"Animation 1.3\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-sprite-animation-v-2-better-coding-test-it-checking-fps-on-the-screen\/\",\"Animation 1.2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-how-to-display-the-frame-rate-fps-on-the-screen\/\",\"Display Frame rate\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-sprite-animation-update\/\",\"Animation 1.1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platformer-1\/\",\"Pygame Platform Game 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-platform-game-2\/\",\"Pygame Platform 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-3-recap-cheatsheet\/\",\"Pygame PLatform 3 - recap and some Cheat Sheet\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-4-background-and-stuffs\/\",\"Pygame Platform 4 - Background & organizing code\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-5-sounds-and-mixer\/\",\"Pygame Platform 5 - Sounds\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/platform-game-in-detail-part-1\/\",\"Game in detail part 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/map-maker-1-2\/\", \"Map maker 1.2\"]\r\n\t\t];\r\n\t\t<\/script>\r\n<script>\r\n\t\r\nif (typeof next2 != \"undefined\"){let next2 = 0;}\r\n\t\r\nnext2 = 0;\r\n\thtml = \"\";\/\/<b style='color:coral;font-size:1.2em'>Other posts about \" + title + \"<\/b><br>\";\r\nfor (address of links) \r\n{\r\n\r\n\tif (next2 == 1){\r\n\t\thtml += \"<div style='background:coral'>\";\r\n\t\thtml += \"Next link => <a href='\" + address[0] + \"'>\" + address[1] + \"<\/a>\";\r\n\t\thtml += \"<\/div><br>\";\r\n\t\tnext2 = 0;\r\n\t}\r\n\tif (address[0] == document.URL) {\r\n\t\tnext2 = 1;\r\n\t}\r\n}\r\n\r\nif (typeof next != \"undefined\") {let next = 0;}\r\nif (typeof addressStart != \"undefined\") {let addressStart = \"\";}\r\nnext = 0;\r\naddressStart = \"<a href='\";\r\nfor (address of links) {\r\n\tif (next == 1){\r\n\t\thtml += \">>>\" + addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t\tnext = 0;\r\n\t}\r\n\telse if (addressStart + address[0] != document.URL)\r\n\t{\r\n\t\thtml += addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnext = 1;\r\n\t\tnext_address = address[0]\r\n\t\tnext_title = address[1]\r\n\t\thtml += \"<span style='color:gray'>\" + address[1] + \"<\/span><br>\";\r\n\t}\r\n\r\n}\r\n\r\n\thtml += `<span style=\"font-size:8px\">Powered by <a href=\"https:\/\/pythonprogramming.altervista.org\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2673\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png\" alt=\"\" width=\"70\" height=\"25\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png 156w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2-150x56.png 150w\" sizes=\"auto, (max-width: 70px) 100vw, 70px\" \/>pythonprogramming.altervista.org<\/a><\/span>`\r\n\thtml = \"<div style='background:yellow'>\" + html + \"<\/div>\";\r\n\tdocument.write(html)\r\n<\/script>\r\n\r\n<h3>Other Pygame's posts<\/h3>\r\n\r\n<script>\r\nvar title = \"Pygame's Posts\"\r\nvar links = [\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platformer-1\/\",\"Platform game 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/make-a-platform-game-with-pygame-dafluffypotato\/\",\"DaFluffyPotato Platform Tutorials\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-and-classic-arcade-games-pong\/\",\"Pong Game Full\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-draws-in-colors-app-to-draw-with-pygame\/\",\"PyGameGIF 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-draw-app-with-animation\/\",\"PyGameGIF 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pydraw-2-0-app-to-draw-gif\/\",\"PyDraw 2.0\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-drawing-2\/\",\"Draw with Pygame\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/animation-with-pygame\",\"Sprite animation 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/animation-on-pygame-2-free-characters-and-more-actions\/\",\"Sprite animation 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/starting-with-pygame\/\",\"Starting movements with Pygame\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-3-move-sprite\/\", \"Move a Sprite\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-4-fonts\/\",\"Text and Fonts\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-animate-a-sprite\/\", \"Animate a sprite\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-and-mouse-events\/\",\"Mouse events\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pgp-aka-pygamepresentation-project\/\",\"Pygame presentation\"],\r\n\t[\"https:\/\/pythonprogramming.altervista.org\/moving-the-player-in-pygame-with-key-get_pressed\/\",\"How to use key.get_pressed()\"]\r\n]\r\n<\/script>\r\n\r\n\r\n<script>\r\n\t\r\nif (typeof next2 != \"undefined\"){let next2 = 0;}\r\n\t\r\nnext2 = 0;\r\n\thtml = \"\";\/\/<b style='color:coral;font-size:1.2em'>Other posts about \" + title + \"<\/b><br>\";\r\nfor (address of links) \r\n{\r\n\r\n\tif (next2 == 1){\r\n\t\thtml += \"<div style='background:coral'>\";\r\n\t\thtml += \"Next link => <a href='\" + address[0] + \"'>\" + address[1] + \"<\/a>\";\r\n\t\thtml += \"<\/div><br>\";\r\n\t\tnext2 = 0;\r\n\t}\r\n\tif (address[0] == document.URL) {\r\n\t\tnext2 = 1;\r\n\t}\r\n}\r\n\r\nif (typeof next != \"undefined\") {let next = 0;}\r\nif (typeof addressStart != \"undefined\") {let addressStart = \"\";}\r\nnext = 0;\r\naddressStart = \"<a href='\";\r\nfor (address of links) {\r\n\tif (next == 1){\r\n\t\thtml += \">>>\" + addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t\tnext = 0;\r\n\t}\r\n\telse if (addressStart + address[0] != document.URL)\r\n\t{\r\n\t\thtml += addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnext = 1;\r\n\t\tnext_address = address[0]\r\n\t\tnext_title = address[1]\r\n\t\thtml += \"<span style='color:gray'>\" + address[1] + \"<\/span><br>\";\r\n\t}\r\n\r\n}\r\n\r\n\thtml += `<span style=\"font-size:8px\">Powered by <a href=\"https:\/\/pythonprogramming.altervista.org\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2673\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png\" alt=\"\" width=\"70\" height=\"25\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png 156w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2-150x56.png 150w\" sizes=\"auto, (max-width: 70px) 100vw, 70px\" \/>pythonprogramming.altervista.org<\/a><\/span>`\r\n\thtml = \"<div style='background:yellow'>\" + html + \"<\/div>\";\r\n\tdocument.write(html)\r\n<\/script>\n","protected":false},"excerpt":{"rendered":"Send an attachment (a pdf) with Python in an email (gmail)\n<a class=\"moretag\" href=\"https:\/\/pythonprogramming.altervista.org\/send-a-pdf-with-an-email-with-python\/\"> [...]<\/a>","protected":false},"author":1,"featured_media":5501,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[1,775],"tags":[780,770,781,4],"class_list":["post-5497","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples","category-pdf","tag-attachment","tag-email","tag-mime","tag-python"],"avopt_banners_inside_post":true,"avopt_banners_on_page":true,"av_copy_from":"","av_sharing_message":"","av_sharing_allowed":true,"av_sharing_on":{"fb":[],"tw":[]},"av_allow_affiliate_banner":false,"av_allow_affiliate_multi_banner":false,"av_show_affiliation_buy_button":false,"av_post_rating":true,"av_have_post_rating_value":false,"av_is_artificial_intelligence_content":false,"_links":{"self":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/5497","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/comments?post=5497"}],"version-history":[{"count":7,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/5497\/revisions"}],"predecessor-version":[{"id":5505,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/5497\/revisions\/5505"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media\/5501"}],"wp:attachment":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media?parent=5497"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/categories?post=5497"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/tags?post=5497"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}