I have a python script where I send mails to a list of mail IDs.
I'm now trying to send mails from an alias mail ID. I have already created the alias mail in the GSuite.
I have the following code as of now:
user = '[email protected]' # Email userID
password = 'password' # Email password
from_addr = '[email protected]'
from_name = 'User Name'
recipients_addr = '[email protected]'
subject = 'This is subject'
body = "this is mail body"
file_path = [file1,file2]
send_email(user, password, from_addr,from_name, recipients_addr, subject, body, file_path)
The send_email() function:
def send_email(user, password, from_addr,from_name, recipients_addr, cc_addr, subject, body, files_path=None,
server='smtp.gmail.com'):
# assert isinstance(recipents_addr, list)
FROM = from_addr
FROMNAME = from_name
TO = recipients_addr if isinstance(recipients_addr, list) else recipients_addr.split(' ')
CC = cc_addr if isinstance(cc_addr, list) else cc_addr.aplit(' ')
PASS = password
SERVER = server
SUBJECT = subject
BODY = body
msg = mime_init(FROM,FROMNAME, TO, CC, SUBJECT, BODY)
for file_path in files_path or []:
with open(file_path, "rb") as fp:
part = MIMEBase('application', "octet-stream")
part.set_payload((fp).read())
# Encoding payload is necessary if encoded (compressed) file has to be attached.
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(file_path))
msg.attach(part)
if SERVER == 'localhost': # send mail from local server
# Start local SMTP server
server = smtplib.SMTP(SERVER)
text = msg.as_string()
server.send_message(msg)
else:
# Start SMTP server at port 587
server = smtplib.SMTP(SERVER, 587)
server.starttls()
# Enter login credentials for the email you want to sent mail from
server.login(user, PASS)
text = msg.as_string()
# Send mail
server.sendmail(FROM, TO, text)
server.quit()
print('Mail Sent!')
The mime_init() function:
def mime_init(from_addr,from_name, recipients_addr, cc_addr, subject, body):
msg = MIMEMultipart()
msg['From'] = formataddr((from_name, from_addr))
msg['To'] = ','.join(recipients_addr)
msg['CC'] = ','.join(cc_addr)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
return msg
I even tried to pass the alias mail as both email-userid and from address, but it's not working.
I am trying to send the mail from an alias mail ID. can anyone help me on this?
question from:
https://stackoverflow.com/questions/66061531/send-mail-from-alias-mail-id-using-python-smtplib