SMTP server with python3 - python-3.x

I'm trying to send an email to my webmail(yahoo) using python3 but I have some problems with the object. I've tried with different ports(465/587) without any success:
import smtplib
pass='letmein'
sender = 'manolo#yahoo.es'
receivers = ['raul#yahoo.es']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) ### 587)
smtpObj.set_debuglevel(1)
smtpObj.login(sender, pass)
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
except SMTPException:
print("Error: unable to send email")
And this is the error I get:
send: 'ehlo [192.168.0.15]\r\n'
reply: b'250-kubenode501.mail-prod1.omega.ir2.yahoo.com Hello [192.168.0.15] [81.61.24.111])\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-SIZE 41697280\r\n'
reply: b'250 AUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER\r\n'
reply: retcode (250); Msg: b'kubenode501.mail-prod1.omega.ir2.yahoo.com Hello [192.168.0.15] [81.61.24.111])\nPIPELINING\nENHANCEDSTATUSCODES\n8BITMIME\nSIZE 41697280\nAUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER'
send: 'AUTH PLAIN AGF1c3RyYWxiaXRAeWFob28uZXMAQWFsaWNpYTAy\r\n'
reply: b'535 5.7.0 (#AUTH005) Too many bad auth attempts.\r\n'
reply: retcode (535); Msg: b'5.7.0 (#AUTH005) Too many bad auth attempts.'
send: 'AUTH LOGIN YXVzdHJhbGJpdEB5YWhvby5lcw==\r\n'
Error: unable to send email
Any idea about how to fix this error?

There are a few things to fix:
Use smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) because port 465 expects connection using SSL.
Add smtpObj.set_debuglevel(1) to have better help with debugging - this will tell you that you need to login first.
Use smtpObj.login("login", "password") before trying to send an email.
The From email should be the same as the login.

Related

SMTP Cpanel giving error smtplib.SMTPDataError: (550)

I am trying to send email using python based on the email id I generated via Cpanel for my domain
import smtplib
with smtplib.SMTP('mail.rottengrapes.com',587) as smtp:
smtp.ehlo()
# smtp.starttls()
smtp.ehlo()
smtp.login("formkitty#rottengrapes.com",config.PASSWORD)
subject = 'Testing email'
body = 'Getting data via email'
msg = f'Subject: {subject}\n\n\n\n{body}'
smtp.sendmail("formkitty#rottengrapes.com",'mewow#gmail.com', msg)
print('printed')
I'm getting the following error
raise SMTPDataError(code, resp) smtplib.SMTPDataError: (550, b'Your
FROM address ( rottengrapes.com , ) must match your
authenticated\nemail domain ( rottengrapes.com ). Treating this as a
spoofed email.')

Server.sendmail() sets my recipient as a BCC

I am trying to send an email to a specific recipient using python, but my code keeps setting the recipient as a BCC. How do I change this to set it as a normal To?
Thanks!
Here is my code
import smtplib
def send_email(subject, msg):
login = "My_email"
password = "password"
reciever = "recipient#gmail.com"
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(login, password)
message = 'Subject: {}\n\n{}'.format(subject, msg)
server.sendmail(login, reciever, message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
subject = "Test email"
Sensor_Message = "This has worked"
send_email(subject, Sensor_Message)
I don't know python, but here is what I think the problem is: your message does not contain a To: or Cc: email header containing the recipient's email address.
Because the recipient's email address is in the list of RCPT TO commands sent over SMTP, but not in the email headers, the recipient's MUA (e.g. Gmail, Outlook, Thunderbird, etc.) treats it as a Bcc.
To fix this problem, make sure that the message contains a To: or Cc: header for the recipient.
Unrelated nitpick: the correct spelling is "receiver"
Good luck!

"Connection unexpectedly closed" error while sending email using SES from AWS

So I'm trying to send an email to my self using SMTP and AWS. The email I'm using on my configuration is verified since I'm still using sandbox mode in SES. While running the script I keep getting the error Connection unexpectedly closed even dough I tried to connect with OpenSSL and it connected but it showed a Didn't find STARTTLS in server response, trying anyway... error after connecting.
Here is my code:
MAIL = {}
MAIL['USERNAME'] = 'AKIAXARHTFGFKCDAO7PD'
MAIL['PASSWORD'] = 'BE0tXPq8wteiKZYtgD2TgtfFTGhgFGOhUp3F0lG0uqn'
MAIL['HOST'] = 'email-smtp.eu-central-1.amazonaws.com'
MAIL['PORT'] = 465
# Set user code
code = random.randrange(000000, 999999)
# Send email to user
print(code)
print(current_user.email)
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Ruby - Verification code'
msg['From'] = 'amng835#gmail.com'
msg['To'] = current_user.email
msg.attach(MIMEText(f'Your verification code is: {code}', 'plain'))
try:
server = smtplib.SMTP(MAIL['HOST'], MAIL['PORT'])
server.ehlo()
server.starttls()
server.ehlo()
server.login(MAIL('MAIL_USERNAME'), MAIL('MAIL_PASSWORD'))
server.sendmail('amng835#gmail.com', current_user.email, msg.as_string())
server.close()
except Exception as error:
print('Failed to send message to user')
print(error)
OpenSSL output:
The command:
openssl s_client -connect email-smtp.eu-central-1.amazonaws.com:465 -starttls smtp
The output:
CONNECTED(00000005)
Didn't find STARTTLS in server response, trying anyway...
write:errno=0
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 372 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
My documentation source:
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-smtp.html
There seems to have some issue with port 465.Change the code to below and it will work fine.
MAIL['PORT'] = 587

How to send an email without login to server in Python

I want to send an email without login to server in Python. I am using Python 3.6.
I tried some code but received an error. Here is my Code :
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer)
server.set_debuglevel(1)
server.sendmail(fromAddr, toAddr, text)
server.quit()
I expect the mail should be sent without asking user id and password but getting an error :
"smtplib.SMTPSenderRefused: (530, b'5.7.1 Client was not authenticated', 'from#Address.com')"
I am using like this. It's work to me in my private SMTP server.
import smtplib
host = "server.smtp.com"
server = smtplib.SMTP(host)
FROM = "testpython#test.com"
TO = "bla#test.com"
MSG = "Subject: Test email python\n\nBody of your message!"
server.sendmail(FROM, TO, MSG)
server.quit()
print ("Email Send")
import win32com.client as win32
outlook=win32.Dispatch('outlook.application')
mail=outlook.CreateItem(0)
mail.To='To address'
mail.Subject='Message subject'
mail.Body='Message body'
mail.HTMLBody='<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment="Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
The code below worked for me.
First, I opened/enabled Port 25 through Network Team and used it in the program.
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer,25)
server.ehlo()
server.starttls()
server.sendmail(fromAddr, toAddr, text)
server.quit()
First, you have to have a SMTP server to send an email. When you don't have one, usually outlook's server is used. But outlook only accepts authenticated users, so if you don't want to login into the server, you have to pick a server that doesn't need authentication.
A second approach is to setup an internal SMTP server. After you setup the internal SMTP server, you can use the "localhost" as the server to send the email. Like this:
import smtplib
receiver = 'someonesEmail#hisDomain.com'
sender = 'yourEmail#yourDomain.com'
smtp = smtplib.SMTP('localhost')
subject = 'test'
body = 'testing plain text message'
msg = 'subject: ' + subject + ' \n\n' + body
smtp.sendmail('sender', receiver, msg)

NodeJS SimpleSMTP server NOT make authentification

I try to use NodeJS SimpleSMTP. Get source from GIT (NodeJS SimpleSMTP)
And try add auth into smtp. My code is:
var SMTP_PORT = 2000;
var smtp = simplesmtp.createServer({debug:true, enableAuthentication:true});
smtp.listen(SMTP_PORT, function(err) {
if (err) console.log(err);
});
smtp.on("authorizeUser", function(connection, username, password, callback){
callback(null, true );
});
smtp.on("startData", function(connection){
console.log("Message from:", connection.from);
console.log("Message to:", connection.to);
});
smtp.on("data", function(connection, chunk){
});
smtp.on("dataReady", function(connection, callback){
console.log("Incoming message saved to /tmp/message.txt");
callback(null, "ABC1"); // ABC1 is the queue id to be advertised to the client
});
And for test I write simple client on Python:
smtpObj = smtplib.SMTP('localhost',2000)
smtpObj.set_debuglevel(1)
smtpObj.login('aaa', 'bbb')
sender="sender#email.com"
toemail = "recv#email.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "my subj"
msg['From'] = sender
msg['To'] = "recv.email.com"
msg.attach(MIMEText("Hello world!",'html'))
smtpObj.sendmail(sender, [toemail], msg.as_string())
If I comment smtpObj.login('aaa', 'bbb') everything is OK, but I need auth user before send email. For auth in Simple SMTP I should use event authorizeUser and option enableAuthentication:true.
What I do wrong? Why server is not make authentification.
My logs:
Python with show debug info:
send: 'ehlo [127.0.1.1]\r\n'
reply: '250-mypc at your service, [127.0.0.1]\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250 STARTTLS\r\n'
reply: retcode (250); Msg: mypc at your service, [127.0.0.1]
8BITMIME
ENHANCEDSTATUSCODES
STARTTLS
Traceback (most recent call last):
File "/home/atlete/work/python/smtptest/src/test.py", line 6, in <module>
server.login("aaa", "bbb")
File "/usr/lib/python2.7/smtplib.py", line 576, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
NodeJS debug info:
CONNECTION FROM 127.0.0.1
Connection from 127.0.0.1
OUT: "220 mypc ESMTP node.js simplesmtp"
COMMAND: ehlo [127.0.1.1]
OUT: "250-mypc at your service, [127.0.0.1]
250-8BITMIME
250-ENHANCEDSTATUSCODES
250 STARTTLS"
Connection closed to 127.0.0.1
Tough to say without seeing the SMTP logs (set simplesmtp debug:true), but you might check that the python auth method, i.e. LOGIN, matches what you set in the simplesmtp options.

Resources