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!")
Related
So basically I am trying to develop a python program that lets me send emails to my friend's email without signing in. However I get a Error that says smtplib.SMTPRecipientsRefused:
Here is my code..
import smtplib
myemail = 'myemail#gmail.com'
mypassword = 'password'
friendemail = input('Please enter the email of the person:')
with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
subject = input("Subject: ")
body = input('Message:')
msg = f"subject:{subject}\n\n{body}"
smtp.starttls()
smtp.login(myemail,mypassword)
smtp.sendmail(myemail, mypassword, msg)
It would be great if anyone could help! Thank YOU!
I tried to run the code you provided, and there was a problem with the image below, right?
According to the prompt, I changed the parameters of sendmail.
smtp.sendmail(myemail, friendemail, msg)
The parameters here represent: sender's mailbox, recipient's mailbox, and email content.
After the change, I successfully ran it in vscode and sent an email to my friend's Gmail email.
Note: the email name and password should be filled in correctly and can not be omitted.
I'm trying to send email to myself with all reports collect each day from my scripts and below is the code I'm using to send the email.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
def send_email(message="", subject="EReport of Twitter Bot"):
msg = MIMEText(message)
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = subject
msg['From'] = 'r****#gmail.com'
msg['To'] = 'r****#gmail.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
try:
s = smtplib.SMTP('smtp.gmail.com',465)
s.ehlo()
s.starttls()
s.ehlo()
s.login('r****#gmail.com', 'mypassword')
s.sendmail('r****#gmail.com', 'r****#gmail.com', msg.as_string())
s.quit()
return True
except Exception as e:
print e
return False
if __name__ == "__main__":
if send_email(message="Hello Ravi!"):
print "Successfully sent the mail"
else:
print "Sorry"
However, I get Connection unexpectedly closed when using the port 465. And If I use port 587 I get the following
(534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvkf\n5.7.14 g4kEFJrti_fMva0wSRWGl4KfuNsFhQumLhgzMCUlPCQn2dvYdPCDr03l9luBP2XTwcnf_N\n5.7.14 BNsPV2jZhLOPjFOSYtGM16Wb6A1BlmLvMP1_mMHoeo4plSVNGio8EDCx_RMW7HcJdYcpx9\n5.7.14 T5SHwceKzRdpUXHxdL2icc0KAMDtb1dDLDr389N_s-tnSkylcN0bwctBA0tKF2k0AC6OsX\n5.7.14 jIcP7iV3ArV6PEB2ZXPCOI2gRPg0> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 lq10sm97657764pab.36 - smtp')
Which basically means my server is not trust worthy, although reverse-dns on my server's ip returns valid rent-history.com
Does anyone know what I can do/try to fix this?
Port 465 is used for SSL, port 587 not.
You should use SMTP_SSL when you intend to use secure connection (port 465), and SMTP with port 587.
Also, I'd like to point out yagmail; I developed it.
You can just use:
import yagmail
yag = yagmail.SMTP('r****#gmail.com', 'pw') # or yagmail.SMTP_SSL for port 465
yag.send('r****#gmail.com', "EReport of Twitter Bot", message)
Furthermore, it makes it easy to:
write the script in a passwordless manner
adding files by filenames (and it will automatically attach it using the correct mimetype)
it automatically sends HTML emails and uses plain text fallback
Install using pip (works for both python 2 and 3):
pip install yagmail
You may need to log into whatever gmail account you are using and go to the less secure apps secion to enable access via a less secure app, such as your program. Obviously, this decreases the account's security, so I don't recommend you do this with a personal account.
I have a script that will be running nightly. I want it to send me an email when it fails to complete. I wrote a short test script to learn how to send an email with Python. In my IDE it runs without error messages but no email. I'm running from one of our servers (not the email server) which doesn't have any email restrictions.
I tried it in the Python shell so I can read any messages:
I tried sending to my gmail account and it get this error:
SMTPRecipientsRefused: {'blahblahblah#gmail.com': (550, '5.7.1 Unable to relay')}
Any ideas??
More info:
I modified the code found here to work with our email.
def send_email(user, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("workemailserver.com")
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
With this I can send an email to my coworkers, but not myself. No biggie because I can use a coworkers email as the sender. Our "email server" relays the messages to office365, so that's why I cant send to my gmail.
My problem is basically solved. But I was never able to get the "simpler" code on top to work when I had tried sending to coworkers?
SMTPRecipientsRefused: (550, '5.7.1 Unable to relay')
This means the server you used can not relay the message to the target recipient. This usually happens when your email server has configuration issues.
The Python logging library provides a class called "SMTPHandler" that will let me e-mail myself the outputs of logging commands. I've some pasted below some example code I found on a (possibly old) website for the library. I can modify it to get it to work with either gmail or my ISP as the SMTP server, but both cases require my password. I currently know of two possible solutions:
I can hardcode my password, which I'd prefer not to do, since this code finds its way onto a cloud revision control server.
I can file my password away in a text file on my machine and have my code read it, which seems ugly. With a more effort I may be able to store the password encrypted, rather than as plaintext.
I'm using a Mac, and I can e-mail myself by running mail on the command line and get the e-mail just fine. I don't know what mail is doing but it may be able to get my SMTP server details from the same place that Mac Mail reads them from and then use the external SMTP server. I tried setting MAILHOST="localhost" in the Python code below and that didn't work.
Is there a better way than #1 or #2 to get these e-mails to my gmail address?
import logging, logging.handlers
MAILHOST = 'beta'
FROM = 'log_test5#yourdomain.com'
TO = ['arkadi_renko']
SUBJECT = 'Test Logging email from Python logging module (non-buffering)'
def main():
log = logging.getLogger("")
log.setLevel(logging.DEBUG)
hdlr = logging.handlers.SMTPHandler(MAILHOST, FROM, TO, SUBJECT)
hdlr.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))
log.addHandler(hdlr)
log.info("Test email contents")
log.removeHandler(hdlr)
if __name__ == "__main__":
main()
I needed to do the exact same thing. You can give smtplib a try. Something like
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('YOUR_MESSAGE_BODY')
me = 'YOUR_SOURCE#EMAIL.COM'
you = 'YOUR_TARGET#EMAIL.COM'
msg['Subject'] = 'YOUR_MESSAGE_SUBJECT'
msg['From'] = me
msg['To'] = you
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
No password is involved.
If you encounter errors like
...
error: [Errno 61] Connection refused
It probably means you don't have smtp server installed or enabled on your mac, installing postfix (say from macports) should fix that.
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.