How to gmail like forward email? - python

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

Related

Potential workarounds for gmail blocking?

So I have a CSV file that contains about 1000 emails, names, companies, etc. Once I deploy my program, it reaches about 80 emails and then I am assuming Google is blocking me from requesting to reach its server again.
I am thinking that I set a timer, for every 70 emails, delete each in the dataframe, wait a few minutes, and redeploy starting from where it left off, because of the deleted rows. Do you think this would work? If so, how would I build a little timer like this? I can create a tracker, but how to initialize a rerun of the program?
Are there any other potential workarounds? Does it have to do with my code constantly resigning in to Google?
import smtplib
import pandas as pd
class Gmail(object):
def __init__(self, email, password, recepient):
self.email = email
self.password = password
self.recepient = recepient
self.server = 'smtp.gmail.com'
self.port = 465
session = smtplib.SMTP_SSL(self.server, self.port)
session.ehlo
session.login(self.email, self.password)
self.session = session
print('Connected to Gmail account successfully.')
def send_message(self, subject, body):
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.recepient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.recepient,
headers + "\r\n\r\n" + body)
print('- Message has been sent.')
df = pd.read_csv('export.csv', error_bad_lines=False)
for index, row in df.iterrows():
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
comp_name = (row['Account Name'])
print('Email to: ' + comp_name)
per_name = (row['Primary Contact: Full Name'])
print('Email to: ' + per_name)
rec = (row['Primary Contact Email'])
print('Email to: ' + rec)
message_body = 'Hi'
gm = Gmail('email#gmail.com', 'password', rec)
gm.send_message('test', message_body)
print('-- Message for ' + rec + ' (' + comp_name + ') is completed.')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('*********************************')
print('Finish reading through CSV.')
print('*********************************')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
Any thoughts would be really helpful.
Thank you!

Is this an valid example from python's smtplib?

Is this an valid example from Python's smtplib? How, from this example, would one send email without giving the password?
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
You can send emails without using a password assuming the server configuration allow that.

Send e-mail from Python through Zoho

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

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.

error sending multiple mails through smtp

I am trying to develop a small python application that allows it's user to send multiple mails through python, I am using gmail, I have allowed Access for less secure apps, it doesn't send.
I have searched stackoverflow for similar problems, but it seemed that most of the used codes are completely different in implementation, even after trying many of hem, they all through exception
import smtplib
from telnetlib import Telnet
def addSenders(message):
num = input("enter number of recievers : ")
num = int (num)
i = 0
emailList = []
while i < num :
nameStr = input("enter name")
mailStr = input("enter e-mail")
emailList.append(mailStr)
if i == 0:
message += nameStr + " <" + mailStr + ">"
print(message)
else:
message += "," + nameStr + " <" + mailStr + ">"
i = i + 1
return emailList, message
sender = 'xxxx#gmail.com'
password = "xxxx"
message = """From: xxxx xxxx <xxxxx#gmail.com>
To: To """
to, message = addSenders(message)
message += """
MIME-Version: 1.0
Content-type: text/html
Subject: Any Subject!
<h1> Good Morning :D <h1>
"""
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(sender, password)
try:
server.sendmail(sender, [to], message)
print ("Successfully sent email")
except:
print ("Error: unable to send email")
server.quit()
output : Error: unable to send email

Categories

Resources