Mailmessage add attachment

To add an attachment to a mail message using the mailmessage object in Python, you can use the add_attachment() method. Here's an example:

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

msg = MIMEMultipart()
msg['Subject'] = 'Test email with attachment'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'

body = 'This is the body of the email'
msg.attach(MIMEText(body, 'plain'))

attachment = open('path/to/attachment.txt', 'rb')
attachment_data = attachment.read()
attachment_name = 'attachment.txt'
attachment_type = 'text/plain'

attachment_msg = email.mime.application.MIMEApplication(attachment_data, Name=attachment_name)
attachment_msg['Content-Type'] = attachment_type
attachment_msg['Content-Disposition'] = f'attachment; filename="{attachment_name}"'

msg.attach(attachment_msg)

server = smtplib.SMTP('smtp.example.com')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()

In this example, we create a MIMEMultipart message and add a text body to it using the MIMEText class. Then, we open the attachment file in binary read mode ('rb') and read its contents into a string. We create a new MIMEApplication object and set its Name attribute to the attachment name, and its Content-Type and Content-Disposition attributes to specify the attachment type and filename. Finally, we attach the attachment to the message using the attach() method, and send the message using the smtplib library.

Note that you'll need to replace 'path/to/attachment.txt' with the actual path to the attachment file you want to send, and '[email protected]' and '[email protected]' with your actual email addresses.