Python send SMTP and get server response code - python

Now I am able to send the email through python using smtplib, however is there any way I can identify the email bounce back or blacklist issue through the response code returned from SMTP like 200, 504, 500 etc?
Current part of code:
try:
smtpObj.sendmail(sender, recipient, msg.as_string())
smtpObj.close()
except SMTPResponseException as e:
error_code = e.smtp_code
error_messsage = e.smtp_error
print(str(error_code) + ' - ' + str(error_messsage))

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.

Imaplib forward mail from gmail with attachment (Python)

Sorry for my english. I need get mail from gmail(this mail can contains attachments) and forward this mail from another email. Bellow my code for forward mail:
for email_id in reversed(items):
status, data = self.imap.fetch(email_id, "(RFC822)")
if status == 'OK':
if count == 2: // this message contains attachment
message = email.message_from_bytes(data[0][1])
message.replace_header("From", FROM_ADDR)
message.replace_header("To", TO_ADDR)
try:
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(CLIENT_MAIL, CLIENT_PASSWORD)
smtp.sendmail(FROM_ADDR, TO_ADDR, message.as_string())
smtp.quit()
print("send mail")
except BaseException as e:
print(e)
count += 1
This code work if mail contains only text(without attachment)
What's your error message?
Also, if you're using Python 3.2+, have you tried using smtp.send_message(message, FROM_ADDR, TO_ADDR) instead of smtp.sendmail()? It looks like it tries hard to do things more correctly, especially regarding character encoding in the SMTP connection.

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

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

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!

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