• 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
  • 相关阅读:
    Springboot辅助功能(内嵌tomcat服务器)
    JDK 9-17 新特性介绍
    HTTP网络协议与接口测试逻辑
    151. 关于 SAP UI5 XML 视图里控件事件处理函数名称中的 . (点号) 问题的讨论
    基于多尺度注意力网络单图像超分(MAN)
    OpenStack之云计算技术与架构-1
    机器学习-特征选择:如何使用交叉验证精准选择最优特征?
    算法第六节
    黑马点评第一个模块---短信登录实现
    聊聊logback的MDCFilter
  • 原文地址:https://blog.csdn.net/weixin_38396940/article/details/133567468