PyCoder’s Weekly: Issue #390 (Oct. 15, 2019)

#390 – OCTOBER 15, 2019
View in Browser »

The PyCoder’s Weekly Logo


CPython 3.8.0 Released

Assignment expressions, positional-only arguments, = specifier in f-strings, and more. Click the link for the full changelog and download links.
PYTHON.ORG

Cool New Features in Python 3.8

What does Python 3.8 bring to the table? Learn about some of the biggest changes and see you how you can best make use of them.
REAL PYTHON

Join the Slack Team at the Spec Annual Developer Conference

alt

Hear the latest product and tooling enhancements for builders of Slack apps. Learn best practices and apply them in hands-on workshops. Troubleshoot with Slack engineers, ask questions and give feedback to our product team. Enjoy or share 50% off registration with the code S19_ADMIN →
SLACK sponsor

Thousands of Scientific Papers May Be Invalid Due to Misunderstanding Python

Developers assumed that glob.glob() returns a sorted list of files, but it doesn’t. And this led to a number of statistical errors and data discrepancies in several published scientific papers.
MIKE DRISCOLL

The Python range() Function

In this step-by-step course, you’ll master the Python range() function, learn how its implementation differs in Python 3 vs 2, and see how you can use it to write faster and more Pythonic code.
REAL PYTHON video

Meta-Programming in Python

“Meta-programming is an act of building functions and classes who can manipulate code by modifying, wrapping existing code or generating code.”
SAURABH KUKADE

Django 3.0 Beta 1 Released

See the release notes for a list of changes and new features.
DJANGOPROJECT.COM

PyPy V7.2 Released

ARM aarch64 support, new JSON decoder, sandboxing makes a return, …
MOREPYPY.BLOGSPOT.COM

Discussions

Python Jobs

Full Stack Developer (Toronto, ON, Canada)

Beanfield Metroconnect

Backend Developer (Kfar Saba, Israel)

3DSignals

More Python Jobs >>>

Articles & Tutorials

Binning Data With Pandas qcut And cut

Pandas qcut and cut are both used to bin continuous values into discrete buckets or bins. This article explains the differences between the two commands and how to use each.
CHRIS MOFFITT

Emacs: The Best Python Editor?

Learn about using Emacs for Python development. You’ll install and configure Emacs on your selected platform, then write Python code to explore its capabilities. Finally, you’ll run, test, and debug Python code in the Emacs environment.
REAL PYTHON

Python Developers Are in Demand on Vettery

alt

Vettery is an online hiring marketplace that’s changing the way people hire and get hired. Ready for a bold career move? Make a free profile, name your salary, and connect with hiring managers from top employers today →
VETTERY sponsor

How to Read SAS Files in Python With Pandas

Learn how to read SAS (.sas7bdat) files in Python, and how to write a SAS file to CSV using Pandas and pyreadstat.
ERIK MARSJA

Projects & Code

Events

PyCode Conference 2019

October 14 to October 17, 2019
PYCODE-CONFERENCE.ORG

Python Northwest

October 17, 2019
PYNW.ORG.UK

PyLadies Dublin

October 17, 2019
PYLADIES.COM

PyCon China 2019 Beijing Branch

October 19 to October 20, 2019
PYCON.ORG

Python Brasil 2019

October 23 to October 29, 2019
PYTHONBRASIL.ORG.BR


Happy Pythoning!
This was PyCoder’s Weekly Issue #390.
View in Browser »

alt


[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

Planet Python

21 Plugins to Efficiently Manage WordPress Multi-Author Blogs

Running a multi-author WordPress website comes with a different set of challenges compared to a a single author WordPress blog.

You’ll need to plan content, create an editorial workflow, monitor user activity, and make sure that your website is running at peak performance.

This sounds like a lot of work, but luckily there are some really helpful plugins that can make it all go smoothly.

In this article, we will show you the best plugins to efficiently manage multi-author WordPress blogs. These plugins will make your job easier and help authors on your website to be more productive.

The best plugins to manage multi-author WordPress blogs more efficiently

1. PublishPress

PublishPress

PublishPress is the best publishing tool kit for any type of content-rich websites and a must-have plugin for multi-author WordPress blogs

It allows you to create and manage an editorial calendar inside WordPress, followup progress on drafts and article ideas, manage authors, set up custom notifications, and more.

The plugin comes with companion addons which give you powerful set of tools. These addons include Capability Manager Enhanced (to customize user permissions), Revisions (to manage revisions in WordPress), and Press Permit which lets you control viewing permissions on WordPress.

This incredibly powerful plugin helps you every step of the way, from content planning to publishing, while ensuring that nothing slips through the cracks. For more details, see our guide on how to improve your editorial workflow in WordPress.

Bonus: See our guide on how to do keyword research to find blog post ideas.

2. WPForms

WPForms
WPForms is the best WordPress contact form plugin on the market. It allows you to easily build forms using a simple drag and drop form builder.

Their Pro plan also comes with user registration, custom login form, and post-submission addons. This allows you to accept posts on your website without allowing anyone accesses to your WordPress admin area,

For details, see our step by step guide on how to allow users to submit posts to your WordPress website.

3. MemberPress

MemberPress

If you want to build a website where only paid members can submit posts, then you’ll love MemberPress. It is the best WordPress membership plugin and allows you to easily sell subscriptions and memberships plans.

It allows you to easily restrict access to any content based on the user’s membership level. You can also use it with WPForms to create front-end post submission pages.

For detailed instructions, see our guide on how to easily create a membership website in WordPress.

4. TranslatePress

TranslatePress

If you run a multilingual WordPress website, then TranslatePress helps you easily manage translations on your website.

It allows you and other authors on your website to easily translate content on your website with a live preview. You can also use it to translate WordPress themes and plugins as well.

For step by step details, see our tutorial on how to easily translate your WordPress website

Alternatives: WPML, Polylang

5. Sucuri

Sucuri

Sucuri is the best WordPress security plugin to protect your website against unauthorized access, brute force attacks, and hacking.

As a multi-author WordPress site, more people have access to the admin area of your WordPress website. While making sure that your authors can write posts, you would also want to make sure that your admin area is safe and secure.

Sucuri performs regular security checkups and acts as a website firewall. This allows malicious attacks to be blocked even before they reach your website.

6. Pre-Publish Checklist

Pre-Publish Checklist

As the administrator of a multi-author WordPress website, you would want to ensure that all authors follow the editorial process you have set up for your website.

Pre-Publish Checklist helps you add a checklist to the post editor, which allows authors to check everything on the list before publishing or submitting it for review.

7. Simple Local Avatars

Simple Local Avatars

WordPress uses Gravatar to display user avatars in comments and in user profiles. However, some of your users may not have gravatar setup for their email address, or they may simply want to use some other picture on their author profile.

Simple Local Avatars plugin allows users on your WordPress site to upload their own author photo by editing their profile.

8. MonsterInsights

MonsterInsights

MonsterInsights is the best Google Analytics plugin for WordPress. It allows you to easily install Google Analytics in WordPress.

It also shows where your users are coming from, what content is doing well, what users do when viewing your website, and more. This data provides you insights to make an effective content strategy for your website.

Bonus: See the top marketing metrics you must track on all WordPress sites.

9. WP Revisions Control

WP Revisions Control

WordPress automatically saves drafts as revisions. This helps you easily undo changes and revert back to an earlier draft of your article. However, if you run a large multi-author WordPress site then these revisions add up to your WordPress database size.

WP Revisions Control helps you set a number of revisions that WordPress should keep. After that number, WordPress will automatically delete the oldest revision. You can also delete all revisions for a specific post if you want.

To learn more, see our beginner’s guide to WordPress post revisions with step by step instructions on how to use revisions on your blog.

10. Author Avatars List

Author Avatars List

An easy way to attract more authors to write for your website is by showcasing authors prominently on your website. One way to do this is by displaying a list of blog authors.

Author Avatars List plugin allows you to easily add a blog authors list anywhere on your site. It comes with a sidebar widget and you can also use the shortcode to easily add it to a post or page.

11. Adminimize

Adminimize

Adminimize gives admins full control over what users can or cannot see inside the WordPress admin area. Admins of a multi-author blog can use it to disable user access to unnecessary sections.

This enables them to provide a lean and distraction-free writing space for the authors. For more details, see our tutorial on how to hide unnecessary items from WordPress admin.

12. User Notes

User Notes

User notes allow you to leave notes on user profiles. These notes can only be seen by admins and can be very helpful and may serve as a reminder tool.

For example, if an author is not following the deadlines you can add a note to remind yourself that this particular author is a bit careless with the deadlines.

13. Simple Author Box

Simple Author Box

By default, most modern WordPress themes can display an author’s profile pic along with their bio below the article. However, some are not very good at it or you way want to get a bit more control over author bio box.

Simple Author Box helps you easily add an author bio box below articles. You can customize it to match your theme colors, configure what you want to show, and add social sharing buttons with it.

14. Edit Author Slug

Edit Author Slug

WordPress comes with SEO friendly URL structure which allows you to choose URL slugs for your posts and pages. However, there is no option to do so for an author page.

Edit Author Slug plugin allows you to do that. You can simply edit a user profile and change the author URL slug. It also allows you to change the author base.

For more information, see our detailed tutorial on how to change author URL slug and base in WordPress.

15. User Submitted Posts

User Submitted Posts

User Submitted Posts plugin does just what it says, it allows users to submit posts to your website without login or creating an account. This allows you to manage user-submitted content without managing user accounts or giving users access to admin area.

For details, see our guide on how to allow users to submit posts to your WordPress site.

16. Theme My Login

Theme My Login

Theme My Login allows you to create custom WordPress login page for your website. You can also create a front-end registration and profile editing page.

Basically, users will be able to login without having access to the admin area of your website. Theme My Login can be used with other plugins to create a front-end editing experience for your authors.

17. Two Factor

Two-Factor

Two Factor plugin allows you to easily add Two Factor authentication to your website. This adds an extra step to your WordPress login screen and making it difficult for hackers to gain access to your website.

You can generate a one-time password using an app like LastPass Authenticator to finish the login process. For details, see our guide on how to add two-factor authentication in WordPress.

18. WP Security Audit Log

WP Security Audit Log

WP Security Audit Log helps you keep a log of all things happening on your website. This allows you to see when each user logged in, what they did, and all other website activties.

This helps you find an imposter, catch mistakes, block hacking attempts, and more. For details, see our guide on how to how to monitor user activity on your WordPress site.

19. WP Email Users

WP Email Users

WP Email Users plugin allows you to quickly send an email to all authors and registered users on your website. This comes in handy if you want to communicate important announcements, notifications, and site related updates.

You’ll need WP Mail SMTP plugin and a proper SMTP service provider to ensure that your emails reach user’s inbox.

20. Emergency Password Reset

Emergency Password Reset

If you are worried that the security of your WordPress site is compromised, then you need to immediately change all WordPress passwords. Now if you run a multi-author WordPress website, then you need to make sure that all user passwords are changed as well.

Emergency Password Reset plugin allows you to reset all user passwords in WordPress with a single click. It also sends an email to all your users with a link to set new passwords.

For details, see our guide on how to reset passwords for all users in WordPress.

21. User Blocker

User Blocker

User Blocker plugin allows you to easily block an author on your WordPress website without changing their author information or deleting their account.

This helps you make sure that content on your website is not affected while making sure that unwanted users can no longer access the WordPress admin area.

For more information, see our step by step guide on how to block a WordPress user without deleting their account.

That’s all for now.

We hope this article helped you find useful plugins to manage your multi-author WordPress blogs. You may also want to see our proven tips to quickly increase your blog traffic and our ultimate guide on how to speed up your WordPress site.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post 21 Plugins to Efficiently Manage WordPress Multi-Author Blogs appeared first on WPBeginner.

WPBeginner

Podcast.__init__: Andrew’s Adventures In Coderland

Software development is a unique profession in many ways, and it has given rise to its own subculture due to the unique sets of challenges that face developers. Andrew Smith is an author who is working on a book to share his experiences learning to program, and understand the impact that software is having on our world. In this episode he shares his thoughts on programmer culture, his experiences with Python and other language communities, and how learning to code has changed his views on the world. It was interesting getting an anthropological perspective from a relative newcomer to the world of software.

Summary

Software development is a unique profession in many ways, and it has given rise to its own subculture due to the unique sets of challenges that face developers. Andrew Smith is an author who is working on a book to share his experiences learning to program, and understand the impact that software is having on our world. In this episode he shares his thoughts on programmer culture, his experiences with Python and other language communities, and how learning to code has changed his views on the world. It was interesting getting an anthropological perspective from a relative newcomer to the world of software.

Announcements

  • Hello and welcome to Podcast.__init__, the podcast about Python and the people who make it great.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With 200 Gbit/s private networking, scalable shared block storage, node balancers, and a 40 Gbit/s public network, all controlled by a brand new API you’ve got everything you need to scale up. And for your tasks that need fast computation, such as training machine learning models, they just launched dedicated CPU instances. Go to pythonpodcast.com/linode to get a $ 20 credit and launch a new server in under a minute. And don’t forget to thank them for their continued support of this show!
  • You listen to this show to learn and stay up to date with the ways that Python is being used, including the latest in machine learning and data analysis. For even more opportunities to meet, listen, and learn from your peers you don’t want to miss out on this year’s conference season. We have partnered with organizations such as O’Reilly Media, Dataversity, Corinium Global Intelligence, and Data Council. Upcoming events include the combined events of the Data Architecture Summit and Graphorum, Data Council in Barcelona, and the Data Orchestration Summit. Go to pythonpodcast.com/conferences to learn more about these and other events, and take advantage of our partner discounts to save money when you register today.
  • Your host as usual is Tobias Macey and today I’m interviewing Andrew Smith about his anthropological study of software engineering culture in his upcoming book Adventures In Coderland.

Interview

  • Introductions
  • How did you get introduced to Python?
  • Can you start by describing the scope and intent of your work on Adventures In Coderland?
  • What was your motivation for embarking on this particular project?
  • Prior to the start of your research for this book, what was your level of familiarity with software development as a discipline and a cultural phenomenon?
  • How are you approaching the research for this book and to what level of detail are you trying to address the problem space?
  • What are some of the most striking contrasts that you have identified between software engineers and coding culture as it compares to that of a layperson?
  • We met at the most recent PyCon US, which I understand you attended as a means of conducting research for your book. What are some of the notable aspects of the Python community that you discovered while you were attending?
  • What are some of the other programming communities that you have engaged with?
    • What are some of the differentiating factors that you have noticed between the communities that you have interacted with?
  • What are some of the most surprising discoveries that you have made in the process of writing this book?
  • What is your metric for determining when you have gathered enough raw material to complete the book?
  • Now that you have delved into the peculiarities of "coderland", how has it changed your own outlook on both the software industry, and society at large?
  • What advice do you have for the engineers who are listening as it pertains to your experiences in writing your book?

Keep In Touch

Picks

Closing Announcements

  • Thank you for listening! Don’t forget to check out our other show, the Data Engineering Podcast for the latest on modern data management.
  • Visit the site to subscribe to the show, sign up for the mailing list, and read the show notes.
  • If you’ve learned something or tried out a project from the show then tell us about it! Email hosts@podcastinit.com) with your story.
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
  • Join the community in the new Zulip chat workspace at pythonpodcast.com/chat

Linksj

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA


Planet Python

Julien Danjou: Sending Emails in Python — Tutorial with Code Examples

Sending Emails in Python — Tutorial with Code Examples

What do you need to send an email with Python? Some basic programming and web knowledge along with the elementary Python skills. I assume you’ve already had a web app built with this language and now you need to extend its functionality with notifications or other emails sending. This tutorial will guide you through the most essential steps of sending emails via an SMTP server:

  1. Configuring a server for testing (do you know why it’s important?)
  2. Local SMTP server
  3. Mailtrap test SMTP server
  4. Different types of emails: HTML, with images, and attachments
  5. Sending multiple personalized emails (Python is just invaluable for email automation)
  6. Some popular email sending options like Gmail and transactional email services

Served with numerous code examples written and tested on Python 3.7!

Sending an email using an SMTP

The first good news about Python is that it has a built-in module for sending emails via SMTP in its standard library. No extra installations or tricks are required. You can import the module using the following statement:

import smtplib

To make sure that the module has been imported properly and get the full description of its classes and arguments, type in an interactive Python session:

help(smtplib)

At our next step, we will talk a bit about servers: choosing the right option and configuring it.

An SMTP server for testing emails in Python

When creating a new app or adding any functionality, especially when doing it for the first time, it’s essential to experiment on a test server. Here is a brief list of reasons:

  1. You won’t hit your friends’ and customers’ inboxes. This is vital when you test bulk email sending or work with an email database.
  2. You won’t flood your own inbox with testing emails.
  3. Your domain won’t be blacklisted for spam.

Local SMTP server

If you prefer working in the local environment, the local SMTP debugging server might be an option. For this purpose, Python offers an smtpd module. It has a DebuggingServer feature, which will discard messages you are sending out and will print them to stdout. It is compatible with all operations systems.

Set your SMTP server to localhost:1025

python -m smtpd -n -c DebuggingServer localhost:1025

In order to run SMTP server on port 25, you’ll need root permissions:

sudo python -m smtpd -n -c DebuggingServer localhost:25

It will help you verify whether your code is working and point out the possible problems if there are any. However, it won’t give you the opportunity to check how your HTML email template is rendered.

Fake SMTP server

Fake SMTP server imitates the work of a real 3rd party web server. In further examples in this post, we will use Mailtrap. Beyond testing email sending, it will let us check how the email will  be rendered and displayed, review the message raw data as well as will provide us with a spam report. Mailtrap is very easy to set up: you will need just copy the credentials generated by the app and paste them into your code.

Sending Emails in Python — Tutorial with Code Examples

Here is how it looks in practice:

import smtplib  port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # your password generated by Mailtrap

Mailtrap makes things even easier. Go to the Integrations section in the SMTP settings tab and get the ready-to-use template of the simple message, with your Mailtrap credentials in it. It is the most basic option of instructing your Python script on who sends what to who is the sendmail() instance method:

Sending Emails in Python — Tutorial with Code Examples

The code looks pretty straightforward, right? Let’s take a closer look at it and add some error handling (see the comments in between). To catch errors, we use the try and except blocks.

# The first step is always the same: import all necessary components: import smtplib from socket import gaierror  # Now you can play with your code. Let’s define the SMTP server separately here: port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap  # Specify the sender’s and receiver’s email addresses: sender = "from@example.com" receiver = "mailtrap@example.com"  # Type your message: use two newlines (\n) to separate the subject from the message body, and use 'f' to  automatically insert variables in the text message = f"""\ Subject: Hi Mailtrap To: {receiver} From: {sender} This is my first message with Python."""  try:   # Send your message with credentials specified above   with smtplib.SMTP(smtp_server, port) as server:     server.login(login, password)     server.sendmail(sender, receiver, message) except (gaierror, ConnectionRefusedError):   # tell the script to report if your message was sent or which errors need to be fixed   print('Failed to connect to the server. Bad connection settings?') except smtplib.SMTPServerDisconnected:   print('Failed to connect to the server. Wrong user/password?') except smtplib.SMTPException as e:   print('SMTP error occurred: ' + str(e)) else:   print('Sent')

Once you get the Sent result in Shell, you should see your message in your Mailtrap inbox:

Sending Emails in Python — Tutorial with Code Examples

Sending emails with HTML content

In most cases, you need to add some formatting, links, or images to your email notifications. We can simply put all of these with the HTML content. For this purpose, Python has an email package.

We will deal with the MIME message type, which is able to combine HTML and plain text. In Python, it is handled by the email.mime module.

It is better to write a text version and an HTML version separately, and then merge them with the MIMEMultipart("alternative") instance. It means that such a message has two rendering options accordingly. In case an HTML isn’t be rendered successfully for some reason, a text version will still be available.

import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart  port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap  sender_email = "mailtrap@example.com" receiver_email = "new@example.com"  message = MIMEMultipart("alternative") message["Subject"] = "multipart test" message["From"] = sender_email message["To"] = receiver_email # Write the plain text part text = """\ Hi, Check out the new post on the Mailtrap blog: SMTP Server for Testing: Cloud-based or Local? https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server/ Feel free to let us know what content would be useful for you!"""  # write the HTML part html = """\ <html> <body> <p>Hi,<br> Check out the new post on the Mailtrap blog:</p> <p><a href="https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server">SMTP Server for Testing: Cloud-based or Local?</a></p> <p> Feel free to <strong>let us</strong> know what content would be useful for you!</p> </body> </html> """  # convert both parts to MIMEText objects and add them to the MIMEMultipart message part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2)  # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:   server.login(login, password)   server.sendmail( sender_email, receiver_email, message.as_string() )  print('Sent')

Sending Emails in Python — Tutorial with Code ExamplesThe resulting output

Sending Emails with Attachments in Python

The next step in mastering sending emails with Python is attaching files. Attachments are still the MIME objects but we need to encode them with the base64 module. A couple of important points about the attachments:

  1. Python lets you attach text files, images, audio files, and even applications. You just need to use the appropriate email class like email.mime.audio.MIMEAudio or email.mime.image.MIMEImage. For the full information, refer to this section of the Python documentation.
  2. Remember about the file size: sending files over 20MB is a bad practice.

In transactional emails, the PDF files are the most frequently used: we usually get receipts, tickets, boarding passes, order confirmations, etc. So let’s review how to send a boarding pass as a PDF file.

import smtplib from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText  port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap  subject = "An example of boarding pass" sender_email = "mailtrap@example.com" receiver_email = "new@example.com"  message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject  # Add body to email body = "This is an example of how you can send a boarding pass in attachment with Python" message.attach(MIMEText(body, "plain"))  filename = "yourBP.pdf" # Open PDF file in binary mode # We assume that the file is in the directory where you run your Python script from with open(filename, "rb") as attachment: # The content type "application/octet-stream" means that a MIME attachment is a binary file part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode to base64 encoders.encode_base64(part) # Add header part.add_header("Content-Disposition", f"attachment; filename= {filename}") # Add attachment to your message and convert it to string message.attach(part)  text = message.as_string() # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:   server.login(login, password)   server.sendmail(sender_email, receiver_email, text)  print('Sent')

Sending Emails in Python — Tutorial with Code ExamplesThe received email with your PDF

To attach several files, you can call the message.attach() method several times.

How to send an email with image attachment

Images, even if they are a part of the message body, are attachments as well. There are three types of them: CID attachments (embedded as a MIME object), base64 images (inline embedding), and linked images.

For adding a CID attachment, we will create a MIME multipart message with MIMEImage component:

import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart  port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap  sender_email = "mailtrap@example.com" receiver_email = "new@example.com"  message = MIMEMultipart("alternative") message["Subject"] = "CID image test" message["From"] = sender_email message["To"] = receiver_email  # write the HTML part html = """\ <html> <body> <img src="cid:myimage"> </body> </html> """ part = MIMEText(html, "html") message.attach(part)  # We assume that the image file is in the same directory that you run your Python script from with open('mailtrap.jpg', 'rb') as img:   image = MIMEImage(img.read()) # Specify the  ID according to the img src in the HTML part image.add_header('Content-ID', '<myimage>') message.attach(image)  # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:   server.login(login, password)   server.sendmail(sender_email, receiver_email, message.as_string())  print('Sent')

Sending Emails in Python — Tutorial with Code ExamplesThe received email with CID image

The CID image is shown both as a part of the HTML message and as an attachment. Messages with this image type are often considered spam: check the Analytics tab in Mailtrap to see the spam rate and recommendations on its improvement. Many email clients — Gmail in particular — don’t display CID images in most cases. So let’s review how to embed a base64 encoded image instead.

Here we will use base64 module and experiment with the same image file:

import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import base64  port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap sender_email = "mailtrap@example.com" receiver_email = "new@example.com"  message = MIMEMultipart("alternative") message["Subject"] = "inline embedding" message["From"] = sender_email message["To"] = receiver_email  # We assume that the image file is in the same directory that you run your Python script from with open("image.jpg", "rb") as image:   encoded = base64.b64encode(image.read()).decode()  html = f"""\ <html> <body> <img src="data:image/jpg;base64,{encoded}"> </body> </html> """ part = MIMEText(html, "html") message.attach(part)  # send your email with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:   server.login(login, password)   server.sendmail(sender_email, receiver_email, message.as_string())  print('Sent')

Sending Emails in Python — Tutorial with Code ExamplesA base64 encoded image

Now the image is embedded into the HTML message and is not available as an attached file. Python has encoded our JPEG image, and if we go to the HTML Source tab, we will see the long image data string in the img src attribute.

How to Send Multiple Emails

Sending multiple emails to different recipients and making them personal is the special thing about emails in Python.

To add several more recipients, you can just type their addresses in separated by a comma, add Cc and Bcc. But if you work with a bulk email sending, Python will save you with loops.

One of the options is to create a database in a CSV format (we assume it is saved to the same folder as your Python script).

We often see our names in transactional or even promotional examples. Here is how we can make it with Python.

Let’s organize the list in a simple table with just two columns: name and email address. It should look like the following example:

#name,email John Johnson,john@johnson.com Peter Peterson,peter@peterson.com

The code below will open the file and loop over its rows line by line, replacing the {name} with the value from the “name” column.

import csv import smtplib  port = 2525 smtp_server = "smtp.mailtrap.io" login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap  message = """Subject: Order confirmation To: {recipient} From: {sender} Hi {name}, thanks for your order! We are processing it now and will contact you soon""" sender = "new@example.com" with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:   server.login(login, password)   with open("contacts.csv") as file:   reader = csv.reader(file)   next(reader)  # it skips the header row   for name, email in reader:     server.sendmail(       sender,       email,       message.format(name=name, recipient=email, sender=sender),     )     print(f'Sent to {name}')

In our Mailtrap inbox, we see two messages: one for John Johnson and another for Peter Peterson, delivered simultaneously:

Sending Emails in Python — Tutorial with Code Examples

Sending emails with Python via Gmail

When you are ready for sending emails to real recipients, you can configure your production server. It also depends on your needs, goals, and preferences: your localhost or any external SMTP.

One of the most popular options is Gmail so let’s take a closer look at it.

We can often see titles like “How to set up a Gmail account for development”. In fact, it means that you will create a new Gmail account and will use it for a particular purpose.

To be able to send emails via your Gmail account, you need to provide access to it for your application. You can Allow less secure apps or take advantage of the OAuth2 authorization protocol. It’s a way more difficult but recommended due to the security reasons.

Further, to use a Gmail server, you need to know:

  • the server name = smtp.gmail.com
  • port = 465 for SSL/TLS connection (preferred)
  • or port = 587 for STARTTLS connection
  • username = your Gmail email address
  • password = your password

import smtplib import ssl  port = 465 password = input("your password") context = ssl.create_default_context()  with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:   server.login("my@gmail.com", password)

If you tend to simplicity, then you can use Yagmail, the dedicated Gmail/SMTP. It makes email sending really easy. Just compare the above examples with these several lines of code:

import yagmail  yag = yagmail.SMTP() contents = [ "This is the body, and here is just text http://somedomain/image.png", "You can find an audio file attached.", '/local/path/to/song.mp3' ] yag.send('to@someone.com', 'subject', contents)

Next steps with Python

Those are just basic options of sending emails with Python. To get great results, review the Python documentation and experiment with your own code!

There are a bunch of various Python frameworks and libraries, which make creating apps more elegant and dedicated. In particular, some of them can help improve your experience with building emails sending functionality:

The most popular frameworks are:

  1. Flask, which offers a simple interface for email sending: Flask Mail.
  2. Django, which can be a great option for building HTML templates.
  3. Zope comes in handy for a website development.
  4. Marrow Mailer is a dedicated mail delivery framework adding various helpful configurations.
  5. Plotly and its Dash can help with mailing graphs and reports.

Also, here is a handy list of Python resources sorted by their functionality.

Good luck and don’t forget to stay on the safe side when sending your emails!

This article was originally published at Mailtrap’s blog: Sending emails with Python

Planet Python

Using the Extract Refresh Command in Portals for Tableau

Everyone hates an old data source extract. Well, maybe not everyone, but data analysts sure do! If you’re an analyst or someone who manages data sources for analysts, we’ve made keeping those extracts fresh super simple from within your portal. So, prepare to say goodbye to those “mature” data source extracts and hello to the crispest, freshest extracts as we walk through how to configure the Extract Refresh Command!

Note: Your REST API service user needs to be a Server Admin to be able to create Extract Refresh Commands due to permission restrictions with the Tableau Server REST API.

Enabling the Portal’s Integration Controls

The first thing you’ll need to do is enable the Integration controls. To do this, go to the portal backend > Settings > Portal Settings > Features tab, and flip on the Integration switch within the Functionality section:

Now, you can refresh the page and the Integration menu will be visible at the top. Select that menu > Manage Commands > New Command button:

Once on the page to create a new command, give it a title, a description if you’d like, choose Extract Refresh as the Command Type, choose a Data Source (we load these automatically for you), name the Tableau Schedule that the Extract Refresh will be on, and, finally, choose the frequency for the task to run at. When you’ve completed the configuration, select Create:

Note: If you can’t see the Extract Refresh option for Command Type, be sure the REST API is enabled in the Tableau Server Settings and that the REST service user is a Server Admin. You also need to be sure the data source you choose is an extract and not a live connection.

Successful Command Created

If the creation is successful, you’ll see a Command Created message pop up. This means a new Tableau Schedule with the frequency you specified was created on your server, and the extract refresh was added to that Schedule. The Tableau Server will run this command until you delete it either on the portal or on the server. Superb!

You can also go to Run Commands and run the task on demand. This is useful to get up-to-date data just before a presentation or while building a slide deck. Just hit the blue Play symbol beneath the ACTIONS column:

If you have any questions about using commands in the portal or would like to trial a portal for your company, don’t hesitate to reach out. Have fun keeping those extracts fresh!

The post Using the Extract Refresh Command in Portals for Tableau appeared first on InterWorks.

InterWorks