import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # Create a multipart message with text and attachment msg = MIMEMultipart() msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Email with attachment' # Add text to the message body body = MIMEText('Hello, this is the email message.') msg.attach(body) # Add an attachment to the message with open('example.pdf', 'rb') as file: attach = MIMEApplication(file.read(),_subtype='pdf') attach.add_header('Content-Disposition', 'attachment', filename='example.pdf') msg.attach(attach) # Send the email smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login('[email protected]', 'password') smtp.sendmail('[email protected]', '[email protected]', msg.as_string()) smtp.quit()In this example, a multipart message is created using the MIMEMultipart class. The sender, recipient, and subject headers are added to the message. The message body is created using the MIMEText class and added to the message using the attach() method. An attachment is added to the message by opening a file, reading its contents, creating a MIMEApplication object with the file contents and filename, and then attaching it to the message using the attach() method. Finally, the email is sent using the SMTP protocol, after encrypting the connection with starttls() command.