Tutorial: Sending an Email using Python

2023-10-05 05:30
文章标签 python using sending email

本文主要是介绍Tutorial: Sending an Email using Python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Tutorial: Sending an Email using Python

In this tutorial, we’ll learn how to send emails, including attachments, using Python.

Table of Contents:

  • Setting Up
  • Crafting the Email
  • Sending the Email
  • Using Gmail as the SMTP Server

Setting Up

Before we begin, we need to set up the email configurations:

import smtplib
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders# Email configurations
SMTP_SERVER = 'smtp.your-email-provider.com'
SMTP_PORT = 587  # Common ports: 587 for TLS, 465 for SSL, 25 for non-secure
SENDER_EMAIL = 'your-email@example.com'
SENDER_PASSWORD = 'your-email-password'
RECEIVER_EMAIL = 'receiver-email@example.com'

Replace the placeholders with your actual email configurations.


Crafting the Email

  1. Creating a Basic Email:
msg = EmailMessage()
msg['From'] = SENDER_EMAIL
msg['To'] = RECEIVER_EMAIL
msg['Subject'] = 'Your Subject Here'
msg.set_content('Your email body text here.')
  1. Adding Attachments:

If you want to attach a file, use the following code:

filename = 'path-to-your-file.txt'
with open(filename, 'rb') as attachment:file_data = attachment.read()file_type = mimetypes.guess_type(filename)[0]file_name = os.path.basename(filename)msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

Sending the Email

Now that our email is ready, let’s send it:

with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:server.starttls()  # Upgrade the connection to secure encrypted SSL/TLSserver.login(SENDER_EMAIL, SENDER_PASSWORD)server.send_message(msg)

Using Gmail as the SMTP Server

If you’re using Gmail as your email provider, there are a couple of additional considerations:

  • SMTP Settings for Gmail:
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587  # Use 465 for SSL
  • Less Secure Apps:

For Gmail to allow third-party apps and scripts to send emails, you might need to enable “Less Secure Apps” in your Gmail settings. To enable:

  1. Go to Google Account.
  2. Click on “Security” on the left-hand side.
  3. Scroll down to the “Less secure app access” section.
  4. Toggle the switch to ON.

Note: Always turn off “Less Secure Apps” after you’re done to ensure your account’s security.


Conclusion

Sending emails via Python is straightforward and powerful, especially when integrating into automation tasks, notifications, or reporting systems. Always ensure you’re following best security practices, especially when handling email credentials.

The Complete Codes

import smtplib
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encodersdef send_email_with_attachment():# Email configurationsSMTP_SERVER = 'smtp.example.com'  # Your SMTP serverSMTP_PORT = 587  # Port for SMTP (commonly 587 for TLS, 465 for SSL, 25 for non-secure)SENDER_EMAIL = 'you@example.com'  # Your email addressSENDER_PASSWORD = 'yourpassword'  # Your email passwordRECEIVER_EMAIL = 'colleague@example.com'  # Your colleague's email address# Create a multipart emailmsg = MIMEMultipart()msg['From'] = SENDER_EMAILmsg['To'] = RECEIVER_EMAILmsg['Subject'] = 'Log File from Latest Run'# Email bodybody = 'Dear colleague, attached is the log file from our latest run.'msg.attach(MIMEText(body, 'plain'))# Attach the filefilename = 'output.txt'with open(filename, 'rb') as attachment:part = MIMEBase('application', 'octet-stream')part.set_payload(attachment.read())encoders.encode_base64(part)part.add_header('Content-Disposition', f'attachment; filename= {filename}')msg.attach(part)# Sending the emailwith smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:server.starttls()  # Upgrade the connection to secure encrypted SSL/TLSserver.login(SENDER_EMAIL, SENDER_PASSWORD)server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, msg.as_string())if __name__ == "__main__":send_email_with_attachment()

这篇关于Tutorial: Sending an Email using Python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/3521

相关文章

Python中常用的四种取整方式分享

《Python中常用的四种取整方式分享》在数据处理和数值计算中,取整操作是非常常见的需求,Python提供了多种取整方式,本文为大家整理了四种常用的方法,希望对大家有所帮助... 目录引言向零取整(Truncate)向下取整(Floor)向上取整(Ceil)四舍五入(Round)四种取整方式的对比综合示例应

python 3.8 的anaconda下载方法

《python3.8的anaconda下载方法》本文详细介绍了如何下载和安装带有Python3.8的Anaconda发行版,包括Anaconda简介、下载步骤、安装指南以及验证安装结果,此外,还介... 目录python3.8 版本的 Anaconda 下载与安装指南一、Anaconda 简介二、下载 An

Python自动化处理手机验证码

《Python自动化处理手机验证码》手机验证码是一种常见的身份验证手段,广泛应用于用户注册、登录、交易确认等场景,下面我们来看看如何使用Python自动化处理手机验证码吧... 目录一、获取手机验证码1.1 通过短信接收验证码1.2 使用第三方短信接收服务1.3 使用ADB读取手机短信1.4 通过API获取

python安装whl包并解决依赖关系的实现

《python安装whl包并解决依赖关系的实现》本文主要介绍了python安装whl包并解决依赖关系的实现,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录一、什么是whl文件?二、我们为什么需要使用whl文件来安装python库?三、我们应该去哪儿下

Python脚本实现图片文件批量命名

《Python脚本实现图片文件批量命名》这篇文章主要为大家详细介绍了一个用python第三方库pillow写的批量处理图片命名的脚本,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言源码批量处理图片尺寸脚本源码GUI界面源码打包成.exe可执行文件前言本文介绍一个用python第三方库pi

Python中多线程和多进程的基本用法详解

《Python中多线程和多进程的基本用法详解》这篇文章介绍了Python中多线程和多进程的相关知识,包括并发编程的优势,多线程和多进程的概念、适用场景、示例代码,线程池和进程池的使用,以及如何选择合适... 目录引言一、并发编程的主要优势二、python的多线程(Threading)1. 什么是多线程?2.

Python爬虫selenium验证之中文识别点选+图片验证码案例(最新推荐)

《Python爬虫selenium验证之中文识别点选+图片验证码案例(最新推荐)》本文介绍了如何使用Python和Selenium结合ddddocr库实现图片验证码的识别和点击功能,感兴趣的朋友一起看... 目录1.获取图片2.目标识别3.背景坐标识别3.1 ddddocr3.2 打码平台4.坐标点击5.图

Python自动化Office文档处理全攻略

《Python自动化Office文档处理全攻略》在日常办公中,处理Word、Excel和PDF等Office文档是再常见不过的任务,手动操作这些文档不仅耗时耗力,还容易出错,幸运的是,Python提供... 目录一、自动化处理Word文档1. 安装python-docx库2. 读取Word文档内容3. 修改

Python重命名文件并移动到对应文件夹

《Python重命名文件并移动到对应文件夹》在日常的文件管理和处理过程中,我们可能会遇到需要将文件整理到不同文件夹中的需求,下面我们就来看看如何使用Python实现重命名文件并移动到对应文件夹吧... 目录检查并删除空文件夹1. 基本需求2. 实现代码解析3. 代码解释4. 代码执行结果5. 总结方法补充在

Python自动化办公之合并多个Excel

《Python自动化办公之合并多个Excel》在日常的办公自动化工作中,尤其是处理大量数据时,合并多个Excel表格是一个常见且繁琐的任务,下面小编就来为大家介绍一下如何使用Python轻松实现合... 目录为什么选择 python 自动化目标使用 Python 合并多个 Excel 文件安装所需库示例代码