• 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'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    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
    • 2
    • 3
    • 4
    • 5
    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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/TLS
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.send_message(msg)
    
    • 1
    • 2
    • 3
    • 4

    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
    
    • 1
    • 2
    • 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 encoders
    
    def send_email_with_attachment():
        # Email configurations
        SMTP_SERVER = 'smtp.example.com'  # Your SMTP server
        SMTP_PORT = 587  # Port for SMTP (commonly 587 for TLS, 465 for SSL, 25 for non-secure)
        SENDER_EMAIL = 'you@example.com'  # Your email address
        SENDER_PASSWORD = 'yourpassword'  # Your email password
        RECEIVER_EMAIL = 'colleague@example.com'  # Your colleague's email address
    
        # Create a multipart email
        msg = MIMEMultipart()
        msg['From'] = SENDER_EMAIL
        msg['To'] = RECEIVER_EMAIL
        msg['Subject'] = 'Log File from Latest Run'
    
        # Email body
        body = 'Dear colleague, attached is the log file from our latest run.'
        msg.attach(MIMEText(body, 'plain'))
    
        # Attach the file
        filename = '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 email
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # Upgrade the connection to secure encrypted SSL/TLS
            server.login(SENDER_EMAIL, SENDER_PASSWORD)
            server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, msg.as_string())
    
    if __name__ == "__main__":
        send_email_with_attachment()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
  • 相关阅读:
    Aveva Marine VBNET 编程系列-搭建开发框架
    Linux 系统移植(一)-- 系统组成
    图像数据噪音种类以及Python生成对应噪音
    C#开发的OpenRA游戏之金钱系统(6)
    lazada API 获得商品评论列表
    linux 主机通信 ipv6 配置
    Python基础指令(上)
    开发实用篇——数据层解决方案
    深入理解Spring Boot Starter:概念、特点、场景、原理及自定义starter
    电子电子架构——AUTOSAR信息安全机制有哪些?(上)
  • 原文地址:https://blog.csdn.net/weixin_38396940/article/details/133567468