python MIME attaching multiple attachments to a multipart message - python

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"))

Related

Receiving - SMTP instance has no attribute error

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'))

Get data in email body with Python

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.

Unable to send html file content as email body in python

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.

Send the contents of a CSV as a table in an email?

How can I send the contents of a CSV as a table in an email using Python?
Example file:
name,age,dob
xxx,23,16-12-1990
yyy,15,02-11-1997
you can use smtplib:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# just an example, you format it usng html
html = "<html><body><table><tr><td>name</td><td><age></td><td>dob</td<tr></table></body></html>"
msg1 = MIMEText(html,'html')
msg = MIMEMultipart("test")
msg['Subject'] = "Name of subject"
msg['From'] = "your#email.com"
msg['To'] = "reciver#gmail.com"
msg.attach(msg1)
server = smtplib.SMTP("smpt_server",port) # example smtplib.smtp("smtp.gmail.com,587)
server.starttls()
server.login("your#gmail.com","login_password")
server.sendmail("your#email.com","reciver#gmail.com",msg.as_string())
server.quit()
better you can do:
msg1 = MIMEText(f.open("file.csv").read())
msg.attach(msg1)
Check this link.
Just pass your csv as third argument to server.sendmail() method

Email module in python 3

So I'm following a tutorial to send email in python, the problem is that it was written for python 2 not python 3(which is what I have). So here's what I'm trying to get an answer what is the module for email in python 3? the specific module I'm trying to get is is:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMETex
I also have a feelling that when I get down to this module there will be an error (haven't got there yet because of
the module above giving error
import smtp
Here is the script:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMETex
fromaddr = ("XXXXX#mchsi.com")
toaddr = ("XXXX#mchsi.com")
msg = MIMEMultipart
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = ("test")
body = ("This is a test sending email through python")
msg.attach(MIMEText(body, ('plain')))
import smptlib
server = smptlib.SMPT('mail.mchsi.com, 456')
server.login("XXXXX#mchsi.com", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
text = msg.as_string()
sender.sendmail(fromaddr, toaddr, text)
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
By the way here are some mistakes in your code:
fromaddr = "XXXXX#mchsi.com" # redundant parentheses
toaddr = "XXXX#mchsi.com" # redundant parentheses
msg = MIMEMultipart() # not redundant this time :)
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "test" # redundant parentheses
body = "This is a test sending email through python" # redundant parentheses
msg.attach(MIMEText(body, 'plain')) # redundant parentheses
import smtplib # SMTP! NOT SMPT!!
server = smtplib.SMTP('mail.mchsi.com', 456) # `port` is an integer
server.login("XXXXX#mchsi.com", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX") # on most SMTP servers you should remove domain name(`#mchsi.com`) here
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text) # it's not `sender`

Categories