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 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async

Python实现剪贴板历史管理器

《Python实现剪贴板历史管理器》在日常工作和编程中,剪贴板是我们使用最频繁的功能之一,本文将介绍如何使用Python和PyQt5开发一个功能强大的剪贴板历史管理器,感兴趣的可以了解下... 目录一、概述:为什么需要剪贴板历史管理二、功能特性全解析2.1 核心功能2.2 增强功能三、效果展示3.1 主界面

Python与Java交互出现乱码的问题解决

《Python与Java交互出现乱码的问题解决》在现代软件开发中,跨语言系统的集成已经成为日常工作的一部分,特别是当Python和Java之间进行交互时,编码问题往往会成为导致数据传输错误、乱码以及难... 目录背景:为什么会出现乱码问题产生的场景解决方案:确保统一的UTF-8编码完整代码示例总结在现代软件

Python+Tkinter实现Windows Hosts文件编辑管理工具

《Python+Tkinter实现WindowsHosts文件编辑管理工具》在日常开发和网络调试或科学上网场景中,Hosts文件修改是每个开发者都绕不开的必修课,本文将完整解析一个基于Python... 目录一、前言:为什么我们需要专业的Hosts管理工具二、工具核心功能全景图2.1 基础功能模块2.2 进

Python多重继承慎用的地方

《Python多重继承慎用的地方》多重继承也可能导致一些问题,本文主要介绍了Python多重继承慎用的地方,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录前言多重继承要慎用Mixin模式最后前言在python中,多重继承是一种强大的功能,它允许一个

python+OpenCV反投影图像的实现示例详解

《python+OpenCV反投影图像的实现示例详解》:本文主要介绍python+OpenCV反投影图像的实现示例详解,本文通过实例代码图文并茂的形式给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前言二、什么是反投影图像三、反投影图像的概念四、反向投影的工作原理一、利用反向投影backproj

Python中edge-tts实现便捷语音合成

《Python中edge-tts实现便捷语音合成》edge-tts是一个功能强大的Python库,支持多种语言和声音选项,本文主要介绍了Python中edge-tts实现便捷语音合成,具有一定的参考价... 目录安装与环境设置文本转语音查找音色更改语音参数生成音频与字幕总结edge-tts 是一个功能强大的

使用Python和PaddleOCR实现图文识别的代码和步骤

《使用Python和PaddleOCR实现图文识别的代码和步骤》在当今数字化时代,图文识别技术的应用越来越广泛,如文档数字化、信息提取等,PaddleOCR是百度开源的一款强大的OCR工具包,它集成了... 目录一、引言二、环境准备2.1 安装 python2.2 安装 PaddlePaddle2.3 安装

Python+PyQt5开发一个Windows电脑启动项管理神器

《Python+PyQt5开发一个Windows电脑启动项管理神器》:本文主要介绍如何使用PyQt5开发一款颜值与功能并存的Windows启动项管理工具,不仅能查看/删除现有启动项,还能智能添加新... 目录开篇:为什么我们需要启动项管理工具功能全景图核心技术解析1. Windows注册表操作2. 启动文件

Python datetime 模块概述及应用场景

《Pythondatetime模块概述及应用场景》Python的datetime模块是标准库中用于处理日期和时间的核心模块,本文给大家介绍Pythondatetime模块概述及应用场景,感兴趣的朋... 目录一、python datetime 模块概述二、datetime 模块核心类解析三、日期时间格式化与