'Use SMTP to send email with different email address from authentication - Python 3
Hi I'm trying to use SMTP in python 3 to send an email, but with a different email address that I have authenticated. Is there a way I can do this? Below is my sample code. I know that there are some source working with gmail account, but couldn't find any for normal email.
import smtplib
import datetime
from email.message import EmailMessage
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from dateutil.relativedelta import relativedelta
dateToday = datetime.date.today()
#Create a multipart for attachment
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'Test'
msg.attach(MIMEText('This is a test message'))
part = MIMEBase('application','octet-stream')
#Open a file for attachment
part.set_payload(open("Workbook1.xlsx",'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="Workbook1 (' + str(dateToday) + ').xlsx"')
msg.attach(part)
#Create user name and password for authentication
username = '[email protected]'
password = '1234'
smtp = smtplib.SMTP('mail.example.com', 11)
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
print('Email successfully sent to: ' + msg['To'])
smtp.quit()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
