python smtp gmail authentication error (sending email through gmail smtp server) - python

I have the following code
import smtplib
from email.mime.text import MIMEText
smtpserver = 'smtp.gmail.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin#myhost.com' # for SMTP AUTH, set SMTP username here
smtppass = '123456' # for SMTP AUTH, set SMTP password here
RECIPIENTS = ['online8#gmail.com']
SENDER = 'admin#myhost.com'
msg = MIMEText('dsdsdsdsds\n')
msg['Subject'] = 'The contents of iii'
msg['From'] = 'admin#myhost.com'
msg['To'] = ''online8#gmail.com''
mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(smtpuser, smtppass)
mailServer.sendmail(smtpuser,RECIPIENTS,msg.as_string())
mailServer.close()
this code works fine on my desktop. but it failed with this error
smtplib.SMTPAuthenticationError: (535, '5.7.1 Username and Password not accepted. Learn more at\n5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 21sm4713429agd.11')
on my linux server.
Not sure what went wrong, should i open some port on my linux server?

Port 587 obviously needs to be open, but it probably is (or you wouldn't have gotten the detailed error msg in question). Python 2.5 vs 2.6 should make no difference. I think the issue has to do with "solving a captcha" once on the computer for which logins are currently getting rejected; follow the detailed instructions at the URL in the error message, i.e., http://mail.google.com/support/bin/answer.py?answer=14257

import random,time
for i in range(1,100):
y=random.randint(30,300)
time.sleep(y)
print ("Mailing for fun, Mail No: " + str(i))
msg = MIMEText('Testing mailing \n Mail No:' + str(i))
msg['Subject'] = 'Mail Number: ' + str(i)
Randomizing the mail interval to check smtp behavior :)
With a bit addition n modification, I got this to work to check our intermittent mail bouncing.

Related

Python - Connect to Gmail and send mail - Error 534 InvalidSecondFactor

i want to include sending notifications mails through gmail in my python code.
I followed all the steps to do it:
import smtplib
Enable less secure app
Wait for 1 day
Set 2-verification access
Create 16 digits app password
Change my gmail password with the 16 digits app password
Log into my gmail account
Unlock Display Captcha
Run the code within 10 minutes
I still got the same error:
(534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h25sm8001063qkg.87 - gsmtp')
This is my code:
import smtplib, ssl
port = 465 # For SSL or 465
smtp_server = "smtp.gmail.com"
sender_email = "my_mail#gmail.com" # Enter your address
receiver_email = "my_mail#gmail.com" # Enter receiver address
password = '16digtisapppass' # i've checked I can log in to my gmail account with it
message = """\
Subject: Hi there
This message is sent from Python."""
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', port)
server.ehlo()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
print(e)
# or
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, message)
I've read these other posts:
https://stackabuse.com/how-to-send-emails-with-gmail-using-python/
http://stackoverflow.com/a/27515833/2684304
I'm not a professional coder, so maybe there is something simple that i'm missing.
I don't know what else could I do. Could anyone help me?
gmail port is 587
you are using AT&T port 465 just replace with 587port .
The problem is that the "2-Step Verification" is on your account.
Solutions:
Turn off 2-Step Verification and use your normal password account in your app (see this link for more details)
Sign in with App Passwords, An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on (see this link or link2).

Send email ( python smtp ) to a specific domain (not .Gmail)

import smtplib
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = 'example1#gmail.com'
#Sender
msg['To'] = 'example2#uc.cl'
#Receiver
msg['Subject'] = 'python'
message = ' Wena mimo, como estai mimo'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('example1#gmail.com', 'password')
#login to the account
mailserver.sendmail('example1#gmail.com','example2#uc.cl',msg.as_string())
mailserver.quit()
#I make a code that sends emails to differents mail(example #gmail and
#corporative ) but i try to send mail to XXXXXXXX#uc.cl (https://www.uc.cl) but this mail dont receive the message
This is a code for Python3 in Ubuntu 18.04 I dont know if the problem is the port:587 or the domain uc.cl or the code, maybe the domain uc.cl takes a high level on this security
THis domain its from a University
I assume the school mail server might try to block the mail coming from your python server.
A few things you could try...
Sending the email while connected to the school wifi. Maybe they don't block internal traffic
Try sending to a email server you set up just to check your code is working right
Make a new email account yahoo, etc and login with the code above and try sending to the other accounts you can test with. This should give you a good idea what is occuring.

How to create a free SMTP server

I am not at all familiar with SMTP but I am working on sending emails through Python code. I have the code but I need to pass SMTP host name for it to actually work. Is there any service which provides a free SMTP service that I leverage for testing out my code? I looked around to create my own SMTP server but couldn't find something that provides a step by step guide to create a SMTP server. I want to create a free server(or if there is any free service) that will provide me with a host name(ip address) so that I can put that host name in my python code and execute it from any machine.
If anyone can point me in the right direction it will be helpful.
import smtplib
username = 'user'
password = 'pwd'
from_addr = 'username#gmail.com'
to_addrs = 'username#gmail.com'
msg = "\r\n".join([
"From: username#gmail.com",
"To: username#gmail.com",
"Subject: subject",
"",
"message"
])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
You can use mutt linux command also here.
See :
https://docs.python.org/3/library/smtplib.html
https://support.google.com/a/answer/176600?hl=en
You need service like https://mailtrap.io/. You'll get SMTP server address (eventually port number) that you point your application to. All e-mails produced by your application will be then intercepted by mailtrap (thus not delivered to the real To: address).
They offer free variant that seems to be suitable for your needs.

STARTTLS extension not supported by server - Getting this error when trying to send an email through Django and a private email address

I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.
In my settings.py, I have these settings:
EMAIL_HOST = 'mail.privateemail.com'
EMAIL_HOST_USER = 'contact#mysite.com'
EMAIL_HOST_PASSWORD = 'my password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
And I am trying to send the email through a view:
send_mail(
'Subject here',
'Here is the message.',
'contact#mysite.com',
['myname#gmail.com'],
fail_silently=False,
)
However, I get this error:
SMTPException at /
STARTTLS extension not supported by server.
Any idea why? Any help is appreciated.
EDIT
After changing the EMAIL_USE_TLS to False, and also removing it to check both separately, I get this error now:
SMTP AUTH extension not supported by server.
Any idea why? Thanks!
your server mail.privateemail.com does not know what is STARTTLS SMTP Commnad is
this may happen in two cases:
your server (mail.privateemail.com) do not support secure communication at all and you need to use plain, non-encrypted communication.
you are trying to connect to the port that is already using SSL as the communication, then STARTTLS to upgrade connection to secure make no sense whatsoever.
your server is configured improperly and ignores STARTTLS on submission port (587).
Judging, that you are connecting to port 587 which should provide plain communication - it's either 1 or 3.
If you want this just work, remove EMAIL_USE_TLS = True or set it to False, otherwise - SMTP server configuration should be fixed.
You may try SSL instead of TLS by making following changes in settings.py
EMAIL_USE_SSL = True
EMAIL_PORT = 465
hope that helps
Either setup TLS on your mail server or use EMAIL_USE_TLS = False.
I am able to resolve the issue with modifying below line of code, by adding port number with server name:
server = smtplib.SMTP('mail.mycompany.com:587')
Not sure if you have solved the problem yet. I also recently try the 2-month free private email package from NameCheap. Here is my code and it works for me as of Jan 2018:
import smtplib
from email.message import EmailMessage
fromaddr = 'account#yourdomain.com'
toaddrs = "recipient#somedomain.com"
SMTPServer = 'mail.privateemail.com'
port = 465 #587
login = "account#yourdomain.com"
password = "password"
msg = EmailMessage()
msgtxt = "http://www.google.com"+"\n\n"+"This is a test."
msg.set_content(msgtxt)
msg['Subject'] = "Test message"
msg['From'] = fromaddr
msg['To'] = toaddrs
server = smtplib.SMTP_SSL(SMTPServer, port) #use smtplib.SMTP() if port is 587
#server.starttls()
server.login(login, password)
server.send_message(msg)
server.quit()
Hope this help!
PS. You can also use port 587, but you have to use smtplib.SMTP() instead of smtplib.SMTP_SSL(), and also have to un-comment the server.starttls() line.

Python how to find my smtp port no and host

I am trying to use the smtplib package in python to send mail
What should be the host and porr no that I need to specify to the SMTP constructor
This is my working example, I have used this in production.
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login("Sender's email id", "Sender's password")
header = 'To:' + <RECEIVERS EMAIL ID> + '\n' + 'From: ' + <SENDERS'S EMAIL ID> + '\n' + 'Subject:<SUBJECT>'
message = <MESSAGE>
smtpserver.sendmail(SENDER, RECEIVER, message)
smtpserver.close()
Probably the default smtp.gmail.com with port 587.
Please, try yagmail. Disclaimer: I'm the maintainer, but I feel like it can help everyone out!
It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
You'll have to install yagmail first with either:
pip install yagmail # python 2
pip3 install yagmail # python 3
Once you will want to also embed html/images or add attachments, you'll really love the package!
It will also make it a lot safer by preventing you from having to have your password in the code.

Categories

Resources