To send an email using Python, you can utilize the built-in smtplib library. Here's an example code:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_email():
    # Email variables
    sender_email = 'your_email@gmail.com'
    sender_password = 'your_password'
    recipient_email = 'recipient_email@gmail.com'
    subject = 'Email Subject'
    body = 'Email Body'

    # Create a MIME message
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = recipient_email
    message['Subject'] = subject

    # Attach body text
    message.attach(MIMEText(body, 'plain'))

    # Attach a file (optional)
    with open('attachment.pdf', 'rb') as file:
        attachment = MIMEApplication(file.read(), _subtype='pdf')
        attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')
        message.attach(attachment)

    # Connect to SMTP server and send email
    smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
    smtp_server.starttls()
    smtp_server.login(sender_email, sender_password)
    smtp_server.sendmail(sender_email, recipient_email, message.as_string())
    smtp_server.quit()

# Call the function to send email
send_email()

Replace the email variables with your own email and password, recipient's email, and email subject and body. If you wish to attach a file, replace the file name and file type as needed.

Python Send Email: Simple Guide with Example Code

原文地址: https://www.cveoy.top/t/topic/njUf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录