My wife has a database of client emails for her work. Because I am studying Python, she asked me to make a program to send automatically the newsletter with the program.
I followed the code of this website :
I made many tests with my mail, her mail, a list of friend's mails (they knew that I will test this), everything worked, with different clients (google, outlook, and so on ...).
Today was the big day to launch the script to send a merry Christmas to her clients. But, for some reasons I ignore, I have this error after a few mails:
Traceback (most recent call last):
File "C:\Users\???\Documents\Newsletter\eMailing.py", line 364, in <module>
server.sendmail(email_address, email_receiver, message.as_string())
File "C:\Users\???\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 903, in sendmail
raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (550, b'Message was not accepted -- invalid mailbox. Local mailbox client@address.com is unavailable: Invalid mPOP user address')
I censored the mail address. Is it possible to skip the error, and continue the program?
The code is in a for loop:
email_list = cleaned_email_list
counter_mails = 0
for mail in email_list:
email_receiver = mail
# Creation of eMail
message = MIMEMultipart("alternative")
# Subject
message["Subject"] = "Музыка для твоего вдохновения"
# From
message["From"] = email_address
# To
message["To"] = email_receiver
# Creation of the text of the mail in raw
text = '''
'''
# Ceation of the text with HTML
html = '''
<html>
I deleted the code in HTML because it's too long but there is a mail in HTML here
</html>
'''
# Creation of elements MIMEText
texte_mime = MIMEText(texte, 'plain')
html_mime = MIMEText(html, 'html')
# Gluing elements
message.attach(texte_mime)
message.attach(html_mime)
# creation of the connexion
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_address, smtp_port, context=context) as server:
# connexion to the account
server.login(email_address, email_password)
# sending the mail
server.sendmail(email_address, email_receiver, message.as_string())
print("Mail sent to :", mail)
counter_mails += 1
print('\n')
print('Total mails sent : ', counter_mails)
I tried to find a solution, looks like it exist a solution with the function try, but I didn't get how it works.
I would like this: when I can't send the mail, instead of the error, it jumps to the next step, doesn't execute this:
print("Mail sent to :", mail)
counter_mails += 1
and goes back to the " for mail in email_list: " and continues until the end of the list.
There is an answer here: The answer
The problem, I didn't understand where to put the code:
except SMTPResponseException as e:
error_code = e.smtp_code
error_message = e.smtp_error
Do I need to put this too?
try:
smtpObj = smtplib.SMTP('smtp.gmail.com',587)
smtpObj.starttls()
smtpObj.login(sender,'foo@bar.com')
smtpObj.sendmail(sender, receivers, message)