本文主要是介绍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
- 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.')
- 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:
- Go to Google Account.
- Click on “Security” on the left-hand side.
- Scroll down to the “Less secure app access” section.
- 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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!