Error when executing email send code in Python function

Question:

I wrote a code to send a confirmation email with Python and it works, but when I put it in the function, sending the code has a problem. Please help me.
code :

import smtplib
import random
verify_code=str(random.randint(1111,9999))
sent_from = 'code@r*****'
password='*******'
to = ['re******@gmail.com']
subject = 'verify code'
body = ('your code is :'+str(code))


email_text = """
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

smtp_server = smtplib.SMTP_SSL('mx2.ta*******.com', 465)
smtp_server.ehlo()
smtp_server.login(sent_from, password)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print ("Email sent successfully!")

and When I put in the function :

def mail(code):
    import smtplib
    import random
    code=str(random.randint(1111,9999))
    sent_from = 'code@r****'
    password='*******'
    to = ['re*******@gmail.com']
    subject = 'verify code'
    body = ('your code is :'+str(code))


    email_text = """
    From: %s
    To: %s
    Subject: %s

    %s
    """ % (sent_from, ", ".join(to), subject, body)
    
    smtp_server = smtplib.SMTP_SSL('mx2.tal*****.com', 465)
    smtp_server.ehlo()
    smtp_server.login(sent_from, password)
    smtp_server.sendmail(sent_from, to, email_text)
    smtp_server.close()
    print ("Email sent successfully!")

Error while executing the function:

This message was created automatically by mail delivery software.

A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:

reza*****@gmail.com
host gmail-smtp-in.l.google.com [108.177.126.27]
SMTP error from remote mail server after end of data:
550-5.7.1 [185.51..] Our system has detected that this message is not RFC
550-5.7.1 5322 compliant:
550-5.7.1 ‘From’ header is missing.
550-5.7.1 To reduce the amount of spam sent to Gmail, this message has been
550-5.7.1 blocked. Please visit
550-5.7.1 https://support.google.com/mail/?p=RfcMessageNonCompliant
550 5.7.1 and review RFC 5322 specifications for more information.

Asked By: Reza Heidary

||

Answers:

Attempt 1 : ratelimit number of emails sent

You are probably sending too many emails at once. Try waiting a few seconds between each email. Since you are using a Gmail account to send emails, you might want to have a look at the email quotas imposed by Google.

Also if you are calling your function in a loop, you are sending multiple emails to the same recipient. The parameter of your function should the email of the recipient instead of code.

import smtplib
import random
import time

def mail(recipient):

    code = str(random.randint(1111, 9999))
    sent_from = 'code@r****'
    password = '*******'
    to = [recipient]
    subject = 'verify code'
    body = ('your code is :'+str(code))
    email_text = """From: %s
    To: %s
    Subject: %s
    
    %s
    """ % (sent_from, ", ".join(to), subject, body)

    smtp_server = smtplib.SMTP_SSL('mx2.tal*****.com', 465)
    smtp_server.ehlo()
    smtp_server.login(sent_from, password)
    smtp_server.sendmail(sent_from, to, email_text)
    smtp_server.close()
    print("Email sent successfully!")


recipient_list = ['[email protected]', '[email protected]']
for recipient in recipient_list:
    mail(recipient)
    time.sleep(1)  # wait 1s before sending next email

Attempt 2 : use CRLF character directly in email_text

The format of the From field field as required by RFC 5322 is :

"From:" mailbox-list CRLF

In Python the CRLF character is rn so lets use it directly in email_text as shown below :

    email_text = (
        """From: %srnTo: %srnSubject: %srnrn%s"""
        % (sent_from, ", ".join(to), subject, body))

This ensures that the correct line breaks are inserted at the right place. (we don’t have to rely on the line breaks inserted by Enter key)

full code with function :

import smtplib
import random


def mail():
    code = str(random.randint(1111, 9999))
    sent_from = 'code@r****'
    password = '*******'
    to = ['re*******@gmail.com']
    subject = 'verify code'
    body = ('your code is :'+str(code))

    email_text = (
        """From: %srnTo: %srnSubject: %srnrn%s"""
        % (sent_from, ", ".join(to), subject, body))

    print(email_text)
    smtp_server = smtplib.SMTP_SSL('mx2.tal*****.com', 465)
    smtp_server.ehlo()
    smtp_server.login(sent_from, password)
    smtp_server.sendmail(sent_from, to, email_text)
    smtp_server.close()
    print("Email sent successfully!")


mail()

Answered By: Bunny
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.