To automate a task I need to get a code sent to me by e-mail in my outlook in order to log into a website. I am new to python, so I was wondering, how can I do it using the win32com module.
Thanks.
You could use smtplib and email.MIME libreries:
This is an example to how send an email from/to a outlook email:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
strFrom = 'email#hotmail.com'
strTo = 'email#hotmail.com'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Email subject'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
body='text, can be plain or html'
msgText_Total=MIMEText(body,'html')
msgAlternative.attach(msgText_Total)
s = smtplib.SMTP('SMTP.Office365.com:587')
s.ehlo()
s.starttls()
s.login('email#hotmail.com','password')
s.sendmail(strFrom, msgRoot["To"].split(","), msgRoot.as_string())
s.quit()
I hope this will helpful for you.
Related
I am trying to automate sending emails to a list of clients using a python script. It worked perfectly before they made it so you can't use the less secure app on 30th May 2022. I added the 2FA password and approved my computer. I am now receiving the error
server.send_message(message)
AttributeError: SMTP instance has no attribute 'send_message' when I try to run my code. Any ideas on how to fix this? I will attach the code below and have of course taken out sensitive information.
Python Code
MY_ADDRESS = "****#gmail.com" # Email Address
MY_PASSWORD = "****Password****" # Emails 2FA Pass
RECIPIENT_ADDRESS = ['****#gmail.com', '****#gmail.com'] # Recipient Address
HOST_ADDRESS = 'smtp.gmail.com'
HOST_PORT = 587
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
# Connection with the server
server = smtplib.SMTP(host=HOST_ADDRESS, port=HOST_PORT)
server.starttls()
server.login(MY_ADDRESS, MY_PASSWORD)
# Creation of the MIMEMultipart Object
message = MIMEMultipart()
# Setup of MIMEMultipart Object Header
message['From'] = MY_ADDRESS
message['To'] = ", ".join(RECIPIENT_ADDRESS)
message['Subject'] = "Test Email - July"
# Creation of a MIMEText Part
textPart = MIMEText("Hello **** & ****,\n\nAttached below is your test bill for the month of July 2022. \n\nBest,\Your Management", 'plain')
# Creation of a MIMEApplication Part
filename = "Test Bill - Billy.pdf"
filePart = MIMEApplication(open(filename,"rb").read(),Name=filename)
filePart["Content-Disposition"] = 'attachment; filename="%s' % filename
# Parts attachment
message.attach(textPart)
message.attach(filePart)
# Send Email and close connection
server.send_message(message)
server.quit()
Try the following code:
import smtplib
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
body_part = MIMEText('Write you text here.')
user = 'xxxx#gmail.com'
password = 'xxxx'
msg['Subject'] = 'You subject'
msg['From'] = formataddr(('yyyyy', 'xxxx#gmail.com'))
msg['To'] = 'yyyy#gmail.com'
msg.attach(body_part)
smtp_obj = smtplib.SMTP_SSL("smtp.gmail.com", 465)
smtp_obj.login(user, password)
smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
smtp_obj.quit()
Update: How to attach a file to your email:
Just add the following lines to the script above.
from email.mime.application import MIMEApplication
path = './../' #The path of your file.
with open(path + filename,'rb') as file:
msg.attach(MIMEApplication(file.read(), Name='filename'))
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'] = 'example2#example.com'
msg['To'] = 'example#example.com'
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 = 'example1#example.com'
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()
I am trying to attach multiple attachments to a email.mime.multipart object:
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart('alternative')
message['Subject'] = 'test'
for i in range(10):
title="<h2>{}</h2>".format(i)
message.attach(MIMEText(title,"html",_charset="utf-8"))
Here I can check that the payload contains the 10 elements:
message.get_payload()
I can see the list of 10 elements, which seems correct.
However when I send the email with the following code:
MAIL_HOST = 'smtp.gmail.com:587'
MAIL_USER = 'xxx#gmail.com'
MAIL_PASSWORD = 'xxx'
MAIL_REPICIENTS = ['xxx#gmail.com']
smtp = SMTP(MAIL_HOST)
smtp.ehlo()
smtp.starttls()
smtp.login(MAIL_USER, MAIL_PASSWORD)
smtp.sendmail(MAIL_USER, MAIL_REPICIENTS, message.as_string())
smtp.close()
The email contains only the last element of the list.
Can anyone help me with that?
That’s because you are attaching 10 different messages. Why you want is to attach one message. Change your code to this:
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart('alternative')
message['Subject'] = 'test'
html = ''
for i in range(10):
title="<h2>{}</h2>".format(i)
html += title
message.attach(MIMEText(html,"html",_charset="utf-8"))
I have a html file whose contents I want to send in the email body using python. Below is the python script:
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import codecs
msg = MIMEMultipart()
# me == my email address
# you == recipient's email address
me = "a#b.com"
you = "b#a.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "Automation Testing"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
f = codecs.open('/Users/test.htm')
html = f.read()
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
composed = msg.as_string()
fp = open('msgtest.txt', 'w')
fp.write(composed)
# Credentials (if needed)
# The actual mail send
server = smtplib.SMTP('smtp.a.com', 25)
server.starttls()
server.sendmail(me, you, composed)
server.quit()
fp.close()
But, it is sending only an empty email with no html content in the body. Please tell me how to fix this.
I saw there are a few somewhat similar questions on stack overflow already, but I couldn't find a solution to my specific problem in them.
I am trying to use Python to send an HTML email with a .pdf attachment. It seems to work fine when I check my email on gmail.com, but when I check the message through apple's Mail program, I do not see the attachment. Any idea what is causing this?
My code is below. A lot of it is copied from various places on stack overflow, so I do not completely understand what each part is doing, but it seems to (mostly) work:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from os.path import basename
import email
import email.mime.application
#plain text version
text = "This is the plain text version."
#html body
html = """<html><p>This is some HTML</p></html>"""
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Deliverability Report"
msg['From'] = "me#gmail.com"
msg['To'] = "you#gmail.com"
# Record the MIME types of both parts - text/plain and text/html
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# create PDF attachment
filename='graph.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
# Attach parts into message container.
msg.attach(att)
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP()
s.connect('smtp.webfaction.com')
s.login('NAME','PASSWORD')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
I'm not sure if it is relevant, but I am running this code on a WebFaction server.
Thanks for the help!
To have text, html and attachments at the same time it is necessary to use both mixed and alternative parts.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
text = "This is the plain text version."
html = "<html><p>This is some HTML</p></html>"
text_part = MIMEText(text, 'plain')
html_part = MIMEText(html, 'html')
msg_alternative = MIMEMultipart('alternative')
msg_alternative.attach(text_part)
msg_alternative.attach(html_part)
filename='graph.pdf'
fp=open(filename,'rb')
attachment = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg_mixed = MIMEMultipart('mixed')
msg_mixed.attach(msg_alternative)
msg_mixed.attach(attachment)
msg_mixed['From'] = 'me#gmail.com'
msg_mixed['To'] = 'you#gmail.com'
msg_mixed['Subject'] = 'Deliverability Report'
smtp_obj = smtplib.SMTP('SERVER', port=25)
smtp_obj.ehlo()
smtp_obj.login('NAME', 'PASSWORD')
smtp_obj.sendmail(msg_mixed['From'], msg_mixed['To'], msg_mixed.as_string())
smtp_obj.quit()
Message structure should be like this:
Mixed:
Alternative:
Text
HTML
Attachment
Use
msg = MIMEMultipart('mixed')
instead of 'alternative'