Sending an Attachment with e-mail using Python - python

I'm trying send an attachment with an e-mail using following code. But it gives an error. Without the attachment it works perfectly. What is the problem with this code?
"mail5.py", line 14
smtpObj = smtplib.SMTP('domain', 25)
^
SyntaxError: invalid syntax
#!/usr/bin/python
import smtplib
sender = 'a#a.com'
receivers = ['b#b.com']
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(file("text.txt").read())
smtpObj = smtplib.SMTP('domain', 25)
smtpObj.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"

It looks like you're missing a closing parenthesis on the preceding line, try this:
msg.attach(MIMEText(file("text.txt").read()))

Related

How to solve smtplib.SMTPDataError: (554, b'5.5.1 Error: no valid recipients') in python

I have to functions send_output_mail which will call process_mail to send mail to the given recipients with multiple attacthments.
Here is my code
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
import pandas as pd
server = '112.11.1.111'; port = 11
MY_ADDRESS = 'xyz#outlook.com'
from datetime import datetime
def process_email(**kwargs): # accept variable number of keyworded arguments
# get total email recipients
rcpt = []
for email in kwargs['emails']:
for i in email:
rcpt.append(i)
# set up the SMTP server
s = smtplib.SMTP(host=server, port=port)
msg = MIMEMultipart() # create a message
# setup the parameters of the message, to cc emails
msg['From'] = MY_ADDRESS
msg['To'] = ','.join(kwargs['emails'][0])
msg['Cc'] = ','.join(kwargs['emails'][1])
msg['Subject'] = kwargs['subject']
if 'attachments' in kwargs.keys():
for attachment in kwargs['attachments']:
fullpath_attactment = os.path.join(os.getcwd(),"Output_file",attachment) #will give full path of the file
with open(fullpath_attactment) as fp:
record = MIMEBase('application', 'octet-stream')
record.set_payload(fp.read())
encoders.encode_base64(record)
record.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(fullpath_attactment))
msg.attach(record)
s.sendmail(MY_ADDRESS, rcpt, msg.as_string()) **#Getting Error Here**
s.quit()
def send_output_mail():
emails = [["xyz#outlook.com", "hy#outlook.com"], ["xxx#outlook.com","yy#outlook.com"]]
subject = "Reports"
process_email(emails=emails, subject=subject, attachments= ["xx.csv","yy.csv"])
Problem
As i Debugged i am getting smtplib.SMTPDataError: (554, b'5.5.1 Error: no valid recipients') while executing line
s.sendmail(MY_ADDRESS, rcpt, msg.as_string())
I have crosschecked and the mailid that i have written and it was also correct, still getting this error.

Email with no attachment is showing paperclip

I am using Python to send a simple HTML email and have the basic code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
def send_test_mail(body):
sender_email = <SenderEmail>
receiver_email = <ReceiverEmail>
msg = MIMEMultipart()
msg['Subject'] = '[Email Test]'
msg['From'] = sender_email
msg['To'] = receiver_email
msgText = MIMEText('<b>%s</b>' % (body), 'html')
msg.attach(msgText)
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 587) as smtpObj:
smtpObj.ehlo()
smtpObj.login(<LoginUserName>, <LoginPassword>)
smtpObj.sendmail(sender_email, receiver_email, msg.as_string())
except Exception as e:
print(e)
if __name__ == "__main__":
send_test_mail("Welcome to Medium!")
This has been put together from a couple of sources from within the stackexchange community but the intention is only to send a straightforward email.
But, when it is received, I get the paperclip icon indicating there is an attachment when there clearly isn't one.
https://i.stack.imgur.com/Ysj3g.png
Python is not my strong point but I'm sure it has more to do with SMTPLIB rather than python.
Does anyone know what is going on here?
Thanks

Multiple recipient is not working in python smtp lib

Im using python 2.7
Im trying to send emails to more than one person. Only one person receives not others.
My code is;
import smtplib
import time
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from utilities.ConfigReader import *
def sendEmailNotification(subject, body):
sender, receiver = getNotificationSettings()
smtpServer, smtpPort, timeout = getSMTPSettings()
msg = MIMEMultipart()
R = receiver.split(",")
body = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = receiver
msg.attach(body)
server = smtplib.SMTP(smtpServer, smtpPort)
server.ehlo()
try:
print receiver
print R
server.sendmail(sender, R, msg.as_string())
except smtplib.SMTPException:
time.sleep(float(timeout))
server.sendmail(sender, R, msg.as_string())
server.quit()
sendEmailNotification("Test","Test")
Here R prints;
['test#lob.com', 'ratha#lob.com']
receiver prints;
test#lob.com, ratha#lob.com
I followed following thread but didnt work to me;
How to send email to multiple recipients using python smtplib?
What im doing wrong here?
I figured out my issue. ratha#lob.com is in the list email test#lob.com . So I haven't received the email for ratha#lob.com , but received for test#lob.com . After changing two private emails, i receive in both emails. So code is working as expected.

Send mail using python to required recipients

I am trying to send email automatically from my official ID to another official ID. For that I have used following python script.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "<SENDER MAIL ID>"
toaddr = "<RECIPIENT MAIL ID>"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "Robot Uprising, We are coming for you"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
While executing this I am facing issue as follows:
Traceback (most recent call last):
File "mailsendtest.py", line 2, in <module>
from email.MIMEMultipart import MIMEMultipart
ImportError: No module named MIMEMultipart
I am a starter in python. Kindly provide inputs. Thanks !
I find two problems with your imports assuming you're using Python3.
Change from email.MIMEMultipart import MIMEMultipart to from email.mime.multipart import MIMEMultipart
Change from email.MIMEText import MIMEText to from email.mime.text import MIMEText
Also make sure you have the libraries installed if these don't work.

Invalid syntax for Python MIMETEXT

I followed a tutorial in youtube for sending email in python using outlook, however I have received an error when running the python file.
This is my python script :
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
sender_email_address = 'nmahirahaqilah.awahab#gmail.com'
sender_email_password = 'mypassword'
receiver_email_address = 'mahirah.abd.wahab#ericsson.com'
email_subject_line = 'Sample python email'
msg = MIMEMultipart()
msg['From'] = sender_email_address
msg['To'] = receiver_email_address
msg['Subject'] = email_subject_line
email_body = 'Hello World'
msg.attach(MIMEText(email_body,'plain'))
email_content = msg.as_string()
server = smtplib.SMTP('smtp.mail.outlook.com:587')
serverstarttls()
server.login(sender_email_address,sender_email_password)
server.sendmail(sender_email_address,receiver_email_address,email_content)
server.quit()
This is the error that I am receiving, not quite sure why:
C:\Users\Azril\Desktop>python email.py
File "email.py", line 3
from email.mime.text
^
SyntaxError: invalid syntax
Appreciate your help on this.

Categories

Resources