Send e-mail from Python through Zoho - python

I'm trying to send an e-mail from Zoho, but: sometimes I receive emails, sometimes not, and it happens also with other persons.
But in mail.zoho.com all emails exists in SENT E-MAILS, but people sometimes did not receive, and it is not a Spam problem.
def sendMailTo(subject='', msgHTML='', to='', no_reply=False, mail_type=None):
try:
j = json.loads(msgHTML)
msgHTML = ""
for k in j.keys():
msgHTML += str(k) + ": " + str(j[k])
msgHTML += "\n"
except ValueError:
pass
#Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg2 = MIMEText(msgHTML, 'html', 'UTF-8') #Content-Type: text/html; charset="us-ascii"
msg.attach(msg2)
# This example assumes the image is in the current directory
import os
os.chdir(os.path.dirname(__file__))
#print(os.getcwd())
fp = open('./utils/images/logo.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<logo>')
msg.attach(msgImage)
fp = open('./utils/images/facebook.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<facebook>')
msg.attach(msgImage)
recipients = [to]
TO = ", ".join(recipients)
msg['Subject'] = subject
msg['To'] = TO
if no_reply:
FROM = "no-reply#xxxxx.com"
msg['From'] = FROM
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP_SSL('smtp.zoho.com', 465)
# s.set_debuglevel(1)
# s.starttls()
s.ehlo()
s.login(FROM, 'yoyoyoyoyoyo')
s.sendmail(FROM, recipients, msg.as_string())
s.quit()
else:
FROM = "xxxxxxxxx#gmail.com"
msg['From'] = FROM
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.gmail.com', 587)
#s.set_debuglevel(1)
#s.ehlo()
s.starttls()
s.login(FROM, 'yoyoyoyoyoyo')
s.sendmail(FROM, recipients, msg.as_string())
s.quit()

Related

Python MIME email attachment sending method sends jpg files as "noname.eml" instead

When I use MIME and SMTPLIB instead of sending my attachment "random.jpg" it sends "noname.eml" which is unopenable and unseeable, I am unable to send attachments correctly for this reason. Why is this caused and how can I solve it?
I tried to change the extension from "png" to "jpg" but the issue pursues.
fromaddr1 = ""
toaddr1 = ""
accpass1 = ""
msg1 = MIMEMultipart()
msg1['From'] = fromaddr1
msg1['To'] = toaddr1
msg1['Subject'] = "YOUR COMPUTER HAS BEEN ACCESSED"
body1 = "Someone has gained access to your computer"
msg1.attach(MIMEText(body1, 'plain'))
filename1 = "random.jpg"
attachment1 = open("random.jpg","rb")
part1 = MIMEBase('application', 'octet-stream')
part1.set_payload((attachment1).read())
encoders.encode_base64(part1)
part1.add_header('Content-Disposition', "attachment1; filename1= %s" %
filename1)
msg1.attach(part1)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr1, accpass1)
text = msg1.as_string()
server.sendmail(fromaddr1, toaddr1, text)
server.quit()
in header:
from email.mime.application import MIMEApplication
instead attachment:
with open(PATH_TO_ZIP_FILE,'rb') as file: msg.attach(MIMEApplication(file.read(), Name='filename.zip'))

Getting error while sending an email using python

I have a script which performs selenium checks and then sends an email with screenshot using ms outlook. Script was working fine. The problem is, sometimes even though the test is successful(try block), it sends out an failure email(except block) and it is intermittent.
Sometimes I get smtplib.SMTPServerDisconnected: Server not connected or smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I've added the below code to open a connection again in case if it is closed, but no luck.
try:
conn = server.noop()[0]
print("---CONNECTION CODE---", conn)
if conn != 250:
server = smtplib.SMTP('mail.xxx.com', 587)
except:
pass
My Script:
class MyTesting:
def AutomationTesting(self):
path = 'C:\\xxxx'
try:
## Selemium test code
msg['From'] = sender
msg['To'] = ", ".join(receiver)
msg['Subject'] = 'Automation Testing Success'
body = 'Hello, \n\nAttached is the screenshot for the reference. \n \nRegards'
msg.attach(MIMEText(body, 'plain'))
attachment = open('C:\\{}'.format(filename), 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
# part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= " + filename)
msg.attach(part)
server = smtplib.SMTP('mail.xxx.com', 587)
conn = server.noop()[0]
try:
conn = server.noop()[0]
print("---CONNECTION CODE---", conn)
if conn != 250:
server = smtplib.SMTP('mail.xxx.com', 587)
except:
pass
server.starttls()
server.login(sender, "Heavensdoor11")
text = msg.as_string()
server.sendmail(sender, receiver, text)
# server.quit()
time.sleep(4)
print("Email sent.")
except:
print("Unable to test site.")
file_write = open(log_file, "a+")
file_write.write("automation failure {}\n".format(timestamp))
file_write.close()
filename_2 = 'Fidelity-Failure' + timestamp + '.png'
driver.get_screenshot_as_file("C:\\{}".format(filename_2))
sender = 'sender '
# receiver = receiver '
msg = MIMEMultipart()
print("Sending an email to {} ...".format(receiver))
msg['From'] = sender
msg['To'] = ", ".join(receiver)
msg['Subject'] = 'Automation Testing Failure'
body = 'Hi Team, \n\nAutomation testing for customer has been failed.'
msg.attach(MIMEText(body, 'plain'))
attachment = open('C:\\{}'.format(filename_2), 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
# part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= " + filename_2)
msg.attach(part)
server = smtplib.SMTP('mail.xxx.com', 587)
server.starttls()
server.login(sender, "mypassword")
text = msg.as_string()
server.sendmail(sender, receiver, text)
# server.quit()
time.sleep(4)
print("Email sent.")
finally:
driver.close()
Any help is really appreciated.

How to gmail like forward email?

Is there any way to forward email(gmail like - you know... with additional text under) using smtp?
Here is a piece of my code:
def forward_email(email_id, email_to):
client, messages = get_original_email(email_id)
typ, data = client.fetch(messages[0].split(' ')[-1], '(RFC822)')
email_data = data[0][1]
message = email.message_from_string(email_data)
smtp = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
smtp.ehlo()
smtp.starttls()
smtp.login(IMAP_LOGIN, IMAP_PASSWORD)
result = smtp.sendmail(email.utils.parseaddr(message['From']),
email_to, message.as_string())
smtp.quit()
return result
Now it's not working because message.as_string() has special headers and other unused info.
I guess gmail blocked it because this.
below code worked for me correctly, even sending mail continuously on function call
def send_email(to='example#email.com', f_host='send.one.com', f_port=587, f_user='from#me.com', f_passwd='my_pass', subject='subject for email', message='content message'):
smtpserver = smtplib.SMTP(f_host, f_port)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(f_user, f_passwd) # from email credentialssssssssss
header = 'To:' + to + '\n' + 'From: ' + f_user + '\n' + 'Subject:' + subject + '\n'
message = header + '\n' + message + '\n\n'
smtpserver.sendmail(f_user, to, str(message))
smtpserver.close()
DBG('Mail is sent successfully!!')

sending emails in a loop In PYTHON 2.7

I am currently trying to make a program that send multiple emails to my self in a loop. I have already written 2 patches of code but i can not seem to get them to work. (I am running this on a raspberry pi so exsuse any weird directorys).
This is my first patch of while loop code
import os
i = 0
while i < 2:
os.pause(4)
os.system("home/Tyler/desktop/test.py")
i += 1
This opens the email "sending" part /\ .
This down here is the "sending" part /
import smtplib
smtpUser = 'smilingexample#gmail.com'
smtpPass = 'password'
toAdd = 'Example#aim.com'
fromAdd = smtpUser
subject = 'yep'
header = 'to: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'hi'
print header + '\n' + body
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header + '\n\n' + body)
s.quit ()
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email import Charset
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
maillist = []
def send_email(messages_list, smtpUser=None, smtpPass=None, tls=False):
failed = []
try:
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
if tls:
s.starttls()
s.ehlo()
if smtpUser and smtpPass:
s.login(smtpUser, smtpPass)
except:
print "ehlo failed"
failed = [x[0] for x in messages_list]
else:
for to_address,from_address,subject,encoding,mesg in messages_list:
try:
if len(mesg) == 2:
msg = MIMEMultipart('alternative')
else:
msg = MIMEText(mesg[0],'plain','utf-8')
msg['Subject'] = "%s" % Header(subject, 'utf-8')
if len(from_address) == 2:
msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[-1])
else:
msg['From'] = from_address[-1]
if len(to_address) == 2:
msg['From'] = "\"%s\" <%s>" % (Header(to_address[0], 'utf-8'), to_address[-1])
else:
msg['To'] = to_address[-1]
msg.set_charset("utf-8")
if len(mesg) == 2:
part1 = MIMEText(mesg[0], 'plain','utf-8')
part2 = MIMEText(mesg[1], 'html','utf-8')
msg.attach(part1)
msg.attach(part2)
s.sendmail(from_address[-1], to_address[-1], msg.as_string())
except:
traceback.print_exc()
failed.append(to_address[-1])
try:
s.quit()
except:
pass
return failed
maillist.append(( ['someone#gmail.com'],["Me","noreply#example.com"],'Subject','utf-8',['text_message','html but you can delete this list element'] ))
for k in send_email(maillist, smtpUser='you#gmail.com', smtpPass='pwd', tls=True):
print k, 'not delivered'
Here's what we use to send alternative Mime messages with alternative body. It is not necessary though so you can send simple text messages as well.
It's prepared to send from localhost but you can easily modify it to use it properly.

printing a list inside a triple quote

I would like to print elements of a list inside an email message.
I defined my list in my python script like:
exceptions = []
At the end of the script the list will have the following elements:
This is a boy.
This is a girl.
This is a dog.
I would like to print the elements of the list called 'exceptions' inside an email that is contrived in the python script.
fromaddr = 'xxx#xxx.com'
toaddrs = 'xxx#xxx.com'
msg = """Subject:Big Bro FTP issue.
From: xxx#xxx.com
To: xxx#xxx.com
!!!PRINT THE EXCEPTION LIST HERE!!!
"""
print "Message length is " + repr(len(msg))
smtp_server = 'xxxxx.com'
smtp_username = 'xxxxxx'
smtp_password = 'xxxxxx'
smtp_port = '587'
smtp_do_tls = True
server = smtplib.SMTP(
host = smtp_server,
port = smtp_port,
timeout = 10
)
server.starttls()
server.ehlo()
server.login(smtp_username, smtp_password)
server.sendmail(fromaddr, toaddrs, msg)
print server.quit()
Any help will be greatly appreciated.
i would prefer MIMEText
import smtplib
from email.mime.multipart import MIMEText
msg = MIMEText("your_maeeage")
msg['From'] = <sender-email>
msg['To'] = <reciver-email>
msg['Subject'] = "your_subject"
server = smtplib.SMTP(<server>,<port>)
server.starttls()
server.login(Username,password)
server.sendmail(from_addr,to_addr,msg.as_string())
Format is a nice method to know which allows you to put place holders in a list. Of course, here you could simple append to the list, but it's useful. Use join to format the list of strings into a single string, here separated by a new line (\n).
msg = """Subject:Big Bro FTP issue.
From: xxx#xxx.com
To: xxx#xxx.com
{}
""".format('\n'.join(exceptions))
or:
msg = """Subject:Big Bro FTP issue.
From: xxx#xxx.com
To: xxx#xxx.com
""" + '\n'.join(exceptions)

Categories

Resources