SMTP with Python, can't send emails to domains other than gmail - python

I'm trying to send an email using a Python script and smtp (I made an account on sendgrid.com), and I found this code on http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/ and I can make it work just fine for gmail, but no other domain seems to receive their test mail. When I check my email activity on sendgrid.com, it tells me the emails have been dropped or bounced because they aren't RFC 5322 compliant. I tried to google this error, but I just can't seem to find a solution.
This is what I have so far:
import smtplib
to = 'example#hotmail.com'
user = 'username'
pwd = 'password'
smtpserver = smtplib.SMTP("smtp.sendgrid.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(user, pwd)
header = 'To:' + to + '\n' + 'From: ' + user + '\n' + 'Subject:Test! \n'
print header
msg = header + '\n Test message \n\n'
smtpserver.sendmail(user, to, msg)
print 'Done!'
smtpserver.close()
Feel free to help me out!

Related

Python SMTP Email Message Body Showing

I have been trying to make the content or message body to appear in the emails but it doesn't appear to be working. It's mentioned that a empty line is needed before the message and with new line after subject. Also, each time I run the script it runs but gives this error "Task timed out after 3.01 seconds" but I get the email, however, the Lambda function is marked as Failed...not sure why?? Maybe that's not so much of a big deal but if it ran then I'm assuming it was successful which is confusing since it says failed. The biggest thing here is the content not showing up. Thank you for any assistance.
import smtplib
sender = 'example.org'
recipient = contact
try:
subject = str(instance_name) + ' Issues'
content="Hello World"
mail = smtplib.SMTP('smtp.office365.com', 587)
mail.ehlo()
mail.starttls()
mail.login('example.org','1234567890')
header = 'To:' + recipient + '\n' + 'From:' \
+sender+'\n'+'subject:' + subject + '\n'
content=header+content
mail.sendmail(sender, recipient, content)
except:
print ("Error: unable to send email")
This works perfectly for me, I hope it will help you out.
import os
import socket
import smtplib
from email.message import EmailMessage
from email.message import EmailMessage
message = EmailMessage()
# Recepients addresses in a list
message['To']=["recepient1#gmail.com","recepient2#gmail.com"]
message['Cc'] = ["cc_recepient#gmail.com"]
message['Bcc'] = ["bcc_recepient#gmail.com"]
message['From'] = "sender#gmail.com"
message['Subject'] = "Subject Matter"
message.set_content("I received the data you sent.")
# Attach a document.
with open("document.txt", "rb") as file:
message.add_attachment(file.read(), maintype="application", subtype="octet-stream",
filename=os.path.basename(file.name))
print(f'Document: {os.path.basename(file.name)} attached successfully.')
# Login in and send your email.
try:
with smtplib.SMTP_SSL("smtp.office365.com", 587) as smtp:
smtp.login('sender#gmail.com', 'password')
print('Sending email...')
smtp.send_message(message)
print(f'Email successfully sent.')
smtp.quit()
except (smtplib.SMTPRecipientsRefused, socket.gaierror):
print ("Error: unable to send email")
I changed this line of code "+sender+'\n'+'subject:' + subject + '\n\n' " and it appears to be working. As far as the timeout issue. I increased it to a minute and it works fine now.

Correct format for IMAP append command in Python? (Yahoo mail)

The following Python function works for outlook, gmail and my shared hosting exim server but when sending mail through yahoo.com it returns this error:
APPEND command error: BAD ['[CLIENTBUG] Additional arguments found after last expected argument']. Data: FHDJ4 APPEND inbox.sent "31-Aug-2016 12:30:45 +0100" {155}
For comparison, outlook returns:
('OK', ['[APPENDUID 105 2] APPEND completed.'])
Gmail returns:
('OK', ['[APPENDUID 14 2] (Success)'])
and Exim returns:
('OK', ['[APPENDUID 1472211409 44] Append completed (0.788 + 0.076 secs).'])
My function uses imaplib2, the arguments passed to it are all strings, and self.username is the sending email address as address#domain.com
My function is:
def send_mail(self, to_addrs, subject, msgtext, verbose=False):
# build message to send
msg = email.message.Message()
msg.set_unixfrom('pymotw')
msg['From'] = self.username
msg['To'] = to_addrs
msg['Subject'] = subject
msg.set_payload(msgtext)
if verbose: print("Sending Mail:\n ", msg)
# connect and send message
server = self.connect_smtp()
server.ehlo()
server.login(self.username, self.password)
server.sendmail(self.username, to_addrs, str(msg))
server.quit()
print("Saving mail to sent")
sentbox_connection = self.imap_connection
print(sentbox_connection.select('inbox.sent'))
print(sentbox_connection.append('inbox.sent', None, imaplib2.Time2Internaldate(time.time()) , str(msg)))
I've tried generating the msg variable with this line instead:
msg = "From: %s\r\n" % self.username + "To: %s\r\n" % to_addrs + "Subject: %s\r\n" % subject + "\r\n" + msgtext
and appending the message using "" instead of None like so:
print(sentbox_connection.append('inbox.sent', None, imaplib2.Time2Internaldate(time.time()) , str(msg)))
Can you tell me what I'm doing wrong? Or if Yahoo has a specific way of handling append commands that I need to account for?
Edit: To clarify, sending the mail works OK for all smtp servers, but appending the sent mail to inbox.sent fails for yahoo
I've resolved this. I noticed the message text did not end with CRLF. Other mail servers were appending this serverside to accept the command, Yahoo does not. The below now works.
I've amended the message payload line to:
msg.set_payload("%s \r\n" % msgtext) # Yahoo is strict with CRLF at end of IMAP command

Sending e-mails using yahoo account in python

I have yahoo account.
Is there any python code to send email from my account ?
Yes, here is the code :
import smtplib
fromMy = 'yourMail#yahoo.com' # fun-fact: "from" is a keyword in python, you can't use it as variable.. did anyone check if this code even works?
to = 'SomeOne#Example.com'
subj='TheSubject'
date='2/1/2010'
message_text='Hello Or any thing you want to send'
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( fromMy, to, subj, date, message_text )
username = str('yourMail#yahoo.com')
password = str('yourPassWord')
try :
server = smtplib.SMTP("smtp.mail.yahoo.com",587)
server.login(username,password)
server.sendmail(fromMy, to,msg)
server.quit()
print 'ok the email has sent '
except :
print 'can\'t send the Email'
I racked my head (briefly) regarding using yahoo's smtp server. 465 just would not work. I decided to go the TLS route over port 587 and I was able to authenticate and send email.
import smtplib
from email.mime.text import MIMEText
SMTP_SERVER = "smtp.mail.yahoo.com"
SMTP_PORT = 587
SMTP_USERNAME = "username"
SMTP_PASSWORD = "password"
EMAIL_FROM = "fromaddress#yahoo.com"
EMAIL_TO = "toaddress#gmail.com"
EMAIL_SUBJECT = "REMINDER:"
co_msg = """
Hello, [username]! Just wanted to send a friendly appointment
reminder for your appointment:
[Company]
Where: [companyAddress]
Time: [appointmentTime]
Company URL: [companyUrl]
Change appointment?? Add Service??
change notification preference (text msg/email)
"""
def send_email():
msg = MIMEText(co_msg)
msg['Subject'] = EMAIL_SUBJECT + "Company - Service at appointmentTime"
msg['From'] = EMAIL_FROM
msg['To'] = EMAIL_TO
debuglevel = True
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.set_debuglevel(debuglevel)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
if __name__=='__main__':
send_email()
Visit yahoo account security page here
You'll need to generate an app password - it's an option towards the bottom of the screen. Use the password Yahoo generated on this page in your script.
To support non-ascii characters; you could use email package:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
# provide credentials
login = 'you#yahoo.com'
password = getpass('Password for "%s": ' % login)
# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ', '.join([login, ])
# send it
s = SMTP_SSL('smtp.mail.yahoo.com', timeout=10) #NOTE: no server cert. check
s.set_debuglevel(0)
try:
s.login(login, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
s.quit()
There are a couple of issues. One is addressed by an answer already posted.
Use TLS (Port 465)
Make sure you have an app password. Yahoo and other email services have updated their authentication practices to limit things that can login without 2 factor authentication. If you want to authenticate with smtplib you need to create an app password here: https://login.yahoo.com/myaccount/security/app-password
If you do that then you'll be able to send emails
For A good year and a half I had the following def working fine on PC's and Pi's. I had a script emailing me every Saturday at noon as a general health check. The working part was..
def my_callback():
server = smtplib.SMTP('smtp.mail.yahoo.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
The about two weeks ago its stopped working on all my devices. Running through the script I found that the "server.starttls()" line was the source of the failure. Investigating around I came to find that reverting to port 465 and SSL, dropping the server.starttls() fixed the Issue.
def my_callback():
server = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465)
server.login(username,password)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
Anybody else have this issue? Have Yahoo changed something?

Sending emails with Gmail OAuth2 and SMTP (Python)

I am developing an application that allows a user to authenticate with Gmail and send an email.
Here is what needs to happen:
user authenticates with OAuth2
user's email address (or any other persistent unique identifier) is obtained and used to log the user into the app
user can compose and send an email using SMTP
However, I'm running into a problem with authentication. The function I am using is OAuth2WebServerFlow():
flow = OAuth2WebServerFlow(client_id=GOOGLE_CLIENT_ID,
client_secret=GOOGLE_CLIENT_SECRET,
scope=scope,
redirect_uri=base_app_url + '/oauth2callback')
This works well when scope='https://mail.google.com/', but the problem is I can't obtain the user's email address because the user hasn't given that permission (as indicated by https://developers.google.com/oauthplayground/). As a result, I've had to hardcode my own email address to get this to work.
On the other hand, when scope='https://mail.google.com/,https://www.googleapis.com/auth/userinfo.email', I can get the user's email address with the following:
r = requests.get('https://www.googleapis.com/oauth2/v2/userinfo',
headers={'Authorization': 'OAuth ' + access_token})
The problem in this case, however, is that when I go to send an email, the access_token that is used to create the auth string is not accepted, giving me the following error (which I believe is an inappropriate one):
SMTPSenderRefused: (535,
'5.7.1 Username and Password not accepted. Learn more at\n5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 cv19sm54718503vdb.5',
u'<MY_NAME#MY_GOOGLE_APP_DOMAIN.COM>')
Here is my code for sending the email:
def send_email(user_address, access_token, recipient_address, subject, body):
xoauth2_string = 'user=%s\1auth=Bearer %s\1\1' % (user_address, access_token)
url = "https://mail.google.com/mail/b/" + user_address + "/smtp/"
conn = smtplib.SMTP('smtp.gmail.com', 587)
conn.set_debuglevel(True)
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(xoauth2_string))
header = 'To:' + recipient_address + '\n'
header += 'From:' + user_address + '\n'
header += 'Subject:' + subject + ' \n'
header += 'Content-Type: text/html; charset=UTF-8\n'
msg = header + '\n ' + body + ' \n\n'
conn.sendmail(user_address, recipient_address, msg)
Basically I want to find out if:
I can get a user's email or some other persistent unique identifier with scope='https://mail.google.com/'.
There is a way to make SMTP work with scope='https://mail.google.com/,https://www.googleapis.com/auth/userinfo.email'.
Why are my auth strings getting rejected? Is there something I'm missing? Is there something wrong with the google api when requesting multiple permissions?

Sending mails to multiple users using python

I recently found a code to send emails using python. It was only for a single user so I modified it to take emails from a txt file which stores the email on every line and then send them mails. However what I found is that the mails end up in the spam folder(in case of Gmail) or the Junk folder (in case of hotmail or live). Is it possible to change the code so that the message lands in the inbox instead of being filtered as spam? Did I get something wrong?
import smtplib,sys
server = 'smtp.gmail.com'
port = 587
sender = 'my-username#gmail.com'
subject = 'Gmail SMTP Test'
body = 'blah blah blah'
"Sends an e-mail to the specified recipient."
session = smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, 'my-password!')
f = open('emails.txt')
for line in f:
recipient = line
print recipient
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient]
headers = "\r\n".join(headers)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
f.close()
session.quit()
That's a very difficult question, because the spam classification is not done by you. (Obviously! If anyone could make their messages "not spam" then of course the spammers would do that too.)
There are various things you should do if you are seriously thinking about sending large-scale email, involving authenticating servers etc. Unless you are an expert, you should engage the services of a mailing company to do them.
I had a similar problem using PHP to send emails and I was able to get my emails out of the spam folder just by changing the subject and body - making them slightly more meaningful and less test-like.
Try out different things - a subject like "Invoice from Jack's Store" or "Introducing you to Twitter." Or just take the subject and the body from an actual email and put it in your test.
Yes One Way is there but there is time wasting method.....
This is your Code:
put the sleep method and replace with this code
import smtplib,sys
import time
server = 'smtp.gmail.com'
port = 587
sender = 'my-username#gmail.com'
subject = 'Gmail SMTP Test'
body = 'blah blah blah'
"Sends an e-mail to the specified recipient."
session = smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, 'my-password!')
f = open('emails.txt')
for line in f:
recipient = line
print recipient
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient]
headers = "\r\n".join(headers)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
time.sleep(3)
f.close()
session.quit()
IF any other problem comment....:)

Categories

Resources