How to forward email using Python - python

First, let me say, I already know that this was asked at Forwarding an email with python smtplib already.
The reason that I am posting something so closely related to that question is that I have tried using the answers to that question, I have tried changing things, I have searched Google and relentlessly monkeyed with this for about 5 hours now, and I am willing to spend a lot more time on this
-- I just thought one of you might have the answer though :)
My problem is as follows, I am trying to forward an email from my gmail to another gmail, and in running as many python script as I can to try this simple task, I still cannot figure it out.
Here is the code that I am running(this is my modified version of what was posted in the other form):
import smtplib, imaplib, email, string
imap_host = "imap.gmail.com"
imap_port = 993
smtp_host = "smtp.gmail.com"
smtp_port = 587
user = "John.Michael.Dorian.4"
passwd = "mypassword"
msgid = 1
from_addr = "John.Michael.Dorian.4#gmail.com"
to_addr = "myotheremail#gmail.com"
# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4_SSL(imap_host, imap_port)
client.login(user, passwd)
client.select()
typ, data = client.search(None, 'ALL')
for mail in data[0].split():
typ, data = client.fetch(msgid, "(RFC822)")
email_data = data[0][1]
client.close()
client.logout()
# create a Message instance from the email data
message = email.message_from_string(email_data)
# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
print message.as_string()
# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.set_debuglevel(1)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.quit()
The return from the SMTP debug says everything went okay, and I know that it is sending because I tried replacing the
smtp.sendmail(from_addr, to_addr, message.as_string())
With
smtp.sendmail(from_addr, to_addr, 'test')
And it worked fine. It prints the message.as_string() fine, and I am at a loss as how to get it to forward the email!
It doesn't have to be with SMTP or IMAP or any of this code(though it would be nice if it was) but I would really like to figure out how to do this.
I know its possible because I managed to do it yesterday, and the computer I was working on(running Windows of course) crashed and the file was gone.
For those of you who are wondering why I do not just set google to forward everything automatically, it is because I want a script that will eventually move a large amount of mail, once.
Thank you everyone!

More than likely, the Received: headers of the original email are causing gmail to drop the message. Try removing all of them before forwarding it.
If that doesn't fix it, print out the headers and code it to remove all of the ones that would not normally be there on a newly composed message.
However, why forward this way? It would be easier to just pull from one IMAP account and push it to another IMAP account directly.
In fact you could use Mozilla Thunderbird to add both accounts and just drag and drop the messages from one to the other.

Related

HTML Email doesn't send (python3)

I'm trying to send an HTML email, however, when I run this code, literally nothing happens. I sit and wait as the program never finishes. What did I do wrong?
import smtplib, ssl, getpass
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "REDACTED"
receiver_email = "REDACTED"
password = getpass.getpass()
html = """
<html>
<head></head>
<body>
<h1>HEADER</h1>
<br>
body<br>
</body>
</html>
"""
msg = MIMEMultipart()
attach = MIMEText(html, 'html')
msg.attach(attach)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg)
server.close()
The msg needs to be flattened to a string before passing it to the sendmail method:
server.sendmail(sender_email, receiver_email, str(msg))
Also, you'll probably want to set some headers on the msg object:
msg.add_header('From', sender_email)
msg.add_header('Subject', 'whatever')
Enabling the debug output for the SMTP object would help to track down these problems, try inserting this line above the server.login call:
server.set_debuglevel(1)
If you're going to be working with email though it may be worth looking in to the email.message.EmailMessage class.
I've found sending mail using gmails SMTP server hard and difficult to work out (The only way I have even gotten it to work is by using a temporary thing that lets me send emails through my email address and only works half the time)
Instead, I suggest sending your email through SendGrid, using their python API, or another service that offers a similar function (Not being biased just have used SendGrid before and found it very easy and reliable) and just send a request to that every time you want to send an email.
I know its a dodgy way to get it to work but its the only way I've been able to send emails through my Gmail account using python :)
(Id comment this as it isn't really an answer but a workaround however I don't have enough reputation)

Using domain email with Yagmail

I'm working in a company that uses Gmail to send and receive emails from a domain email. To make it clearer, let's say it's firstname#company.com.
Right now my goal is to make a simple script that will send the emails using a list from csv file. The code works fine when I use my personal Gmail email, but the problem starts when I change it to my business account - it seems that the script is ignoring the initialization step because it's not #gmail.com.
Not sure if it's needed, but right now I will be happy to at least run the "yagmail 101" code like the one below. Just for reference, I tried the smtplib as well with same result. The two-factor authentication is on, a 16-char password for Windows mail application was created.
#importing the Yagmail library
import yagmail
try:
#initializing the server connection
yag = yagmail.SMTP(user='firstname#company.com', password='mypassword')
#sending the email
yag.send(to='recipient_username#gmail.com', subject='Testing Yagmail', contents='Hurray, it worked!')
print("Email sent successfully")
except:
print("Error, email was not sent")
#importing the Yagmail library
import yagmail
# connect to smtp server.
yag_smtp_connection = yagmail.SMTP( user="user#company.com", password="mypassword",
host='yourSMTPserver')
# email subject
subject = 'Hello'
contents = ['Hello this email send via YAGMAIL']
# send the email
yag_smtp_connection.send('to#gmail.com', subject, contents)
print("Email send!")

smtp error 534 connecting to gmail python3

I've seen a lot of other posts with the same issue, I tried all of the following:
allow access to less secure app on gmail
Unlock token on google
make an app specific password
allow IMAP on gmail
Nothing is working, i still get the same error message:
SMTPAuthenticationError: (534, b'5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/?p=WebLoginRequired s3sm5978501edm.78 - gsmtp')
This is my code on my python jupiter notebook:
sender_email = "xxx#gmail.com"
receiver_email = "yyy#gmail.com"
password = "xxxxxx"
message = MIMEMultipart("alternative")
message["Subject"] = "new properties for rent"
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = "Hi, new properties satisfy your search on daft: %s" % dictionary
html = "<html><body>%s</body></html>" % emailBody
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.ehlo()
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
There's a couple of reasons for this.
But since you exhausted most of them, and after talking in the comments. It's clear that you were sitting behind some sort of VPN or shared internet connection.
Some times, logging in on your account in a browser from this VPN/Shared connection would solve the problem. If not, the fastest and easiest way around this is to swap to a single-user connection (home wifi, dedicated VPS, something where only a handful of users might be sitting).
Common issues are: You're using Tor, a popular VPN provider, a school/company network.
Here's more information on the topic:
https://support.google.com/websearch/answer/86640?hl=en

Trying to send an Email through python with Gmail or Outlook

Hello I am fairly new to python and stumbled upon this cool feauture that with only a few lines of code, python can send emails.
I am currently not sure if the code that I have below works or if its something on my end? Since I am totally new to this I have no way to test if I am on the right track or not.
When running the code, it compiles with no problem but I never receive the messages.
Also, I am sending emails to myself, so I should see them rather quickly.
Here is my Outlook code:
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'myemail#hotmail.com'
mail.Subject = 'Hello this is you!
mail.Body = 'Hello!!!!!!'
mail.HTMLBody = '<h2>This is an H2 message</h2>' #this field is optional
# To attach a file to the email (optional):
attachment = "C:/Users/OneDrive/Documents/Desktop/Social_Network_Ads.csv"
mail.Attachments.Add(attachment)
mail.Send()
Here is my Gmail Code:
import smtplib
fromaddr = 'myemail#gmail.com'
toaddrs = 'myemail#gmail.com'
msg = 'There was a terrible error that occured and I wanted you to know!'
# Credentials (if needed)
username = '###username###'
password = '###password###'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Please let me know why I am not receiving the email or why its showing as not sent?
EDIT:
I am connected to my local hotmail account and I am logged into Gmail, so I am hopping its not a connection issue.
When I go to check my sent folder nothing seems to have been sent

Sending email with python smtplib not working, confused about the "from" field

I'm trying to send an email in python. Here is my code.
import smtplib
if __name__ == '__main__':
SERVER = "localhost"
FROM = "sender#example.com"
TO = ["wmh1993#gmail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO[0], message)
server.quit()
print "Message sent!"
This runs without error, but no email is sent to wmh1993#gmail.com.
Questions
One thing I don't understand about this code --- what restrictions do I have when setting the FROM field?
Do I somehow have to say that it was from my computer?
What is in place to prevent me from spoofing someone else's email?
Or am I at liberty to do that?
This runs without error, but no email is sent to wmh1993#gmail.com.
This usually means, the message was transferred to your MTA (mailserver) on 'localhost', but this server could not relay it to gmail. it probably tried to send a bounce message to "sender#example.com" and that failed as well. or it sent the message successfully but it landed in gmails spam folder (the message could trigger spam rules since it is missing a date header)
One thing I don't understand about this code --- what restrictions do I have when setting the FROM field?
it must be a syntactically valid email address
Do I somehow have to say that it was from my computer?
no. but that could be the problem why it was not delivered. is your computer on a home/dynamic/dial-up IP? gmail (and many many many other providers) don't accept mail from such IPs. the HELO of your mailserver might be wrong, DNS settings might be incorrect etc. you need to check the server logs. you probably have to configure your local mailserver to relay the message via a smarthost instead of trying to contact the target server directly.
What is in place to prevent me from spoofing someone else's email?
not much, that's why we have so much spam from forged adresses. things like SPF/DKIM can help a bit, but the SMTP protocol itself doesn't offer protection against spoofing.
Or am I at liberty to do that?
technically yes.
Well, since you don't specify exactly what kind of email server you are using and its settings, there are several things that might be wrong here.
First of all, you need to specify the HOST and the PORT of your server and connect to it.
Example:
HOST = "smtp.gmail.com"
PORT = "587"
SERVER = smtplib.SMTP()
SERVER.connect(HOST, PORT)
Then you need to specify an user and his password to this host.
Example:
USER = "myuser#gmail.com"
PASSWD = "123456"
Some servers require the TLS protocol.
Example:
SERVER.starttls()
Then you need to login.
Example:
SERVER.login(USER,PASSWD)
Only then you are able to send the email with your sendmail.
This example works pretty well in most common servers.
If you are using, as it seems, your own server, there aren't much changes you need to apply. But you need to know what kind of requirements this server has.
The "from" field in the email headers specifies the sender's email address. When using smtplib in Python to send an email, the "from" field can be set using the "from_address" argument in the smtplib.SMTP function. Here's an example:
import smtplib
sender_email = "sender#example.com"
recipient_email = "recipient#example.com"
message = "Subject: Example Email\n\nThis is an example email."
with smtplib.SMTP("smtp.example.com", 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login("sender#example.com", "password")
smtp.sendmail(sender_email, recipient_email, message)
Note that many email servers may reject emails that have a "from" address that doesn't match the login credentials.

Categories