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的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

python 字典d[k]中key不存在的解决方案

《python字典d[k]中key不存在的解决方案》本文主要介绍了在Python中处理字典键不存在时获取默认值的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录defaultdict:处理找不到的键的一个选择特殊方法__missing__有时候为了方便起见,

使用Python绘制可爱的招财猫

《使用Python绘制可爱的招财猫》招财猫,也被称为“幸运猫”,是一种象征财富和好运的吉祥物,经常出现在亚洲文化的商店、餐厅和家庭中,今天,我将带你用Python和matplotlib库从零开始绘制一... 目录1. 为什么选择用 python 绘制?2. 绘图的基本概念3. 实现代码解析3.1 设置绘图画

Python pyinstaller实现图形化打包工具

《Pythonpyinstaller实现图形化打包工具》:本文主要介绍一个使用PythonPYQT5制作的关于pyinstaller打包工具,代替传统的cmd黑窗口模式打包页面,实现更快捷方便的... 目录1.简介2.运行效果3.相关源码1.简介一个使用python PYQT5制作的关于pyinstall

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

基于Python实现PDF动画翻页效果的阅读器

《基于Python实现PDF动画翻页效果的阅读器》在这篇博客中,我们将深入分析一个基于wxPython实现的PDF阅读器程序,该程序支持加载PDF文件并显示页面内容,同时支持页面切换动画效果,文中有详... 目录全部代码代码结构初始化 UI 界面加载 PDF 文件显示 PDF 页面页面切换动画运行效果总结主