Python Forum

Full Version: email code works in 2.7 but not in 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Running Python 3.8.10 and 2.7.18 under Mint 20.2
I am trying to generate an email on my IONOS 1 & 1 domain using this code
import smtplib
MAIL_2 = ['[email protected]']
FROM_ADDR = '[email protected]'
SUBJECT = 'Mail Subject via Ionos`'
BODY = 'Body of message'
PASSWORD = 'mypasswd'
SMTP_SERVER = "smtp.ionos.co.uk:587"
smtpserver = smtplib.SMTP(SMTP_SERVER)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(FROM_ADDR, PASSWORD)
header = 'To:' + ", " + MAIL_2[0] + '\n' + 'From: ' + FROM_ADDR + '\n' + 'Subject: ' + SUBJECT + '\n'
mmsg = header + '\n' + SUBJECT + '\n' + BODY + '\n\n'
smtpserver.sendmail(FROM_ADDR, MAIL_2,mmsg)
smtpserver.close()
If I run it in Python3 I get this error
Error:
Traceback (most recent call last): File "testmail-ionos01.py", line 14, in <module> smtpserver.starttls() File "/usr/lib/python3.8/smtplib.py", line 783, in starttls self.sock = context.wrap_socket(self.sock, File "/usr/lib/python3.8/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File "/usr/lib/python3.8/ssl.py", line 1040, in _create self.do_handshake() File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: SSLV3_ALERT_ILLEGAL_PARAMETER] sslv3 alert illegal parameter (_ssl.c:1131)
If I run it in Python2.7 it works. I have looked with Wireshark and noticed that with 2.7 it uses TSLv1.3 but with 3.8 it uses TSLv1.2, I don't knw why or if this is relevant.
Also if I run similar code but using a gmail account it works in Python3.
Any idea how I can get this to work in Python3?
Thanks
Mick
In case anyone has the same problem, this code works

import smtplib
MAIL_2 = ['[email protected]']
FROM_ADDR = '[email protected]'
SUBJECT = 'Mail Subject via Ionos`'
BODY = 'Body of message'
PASSWORD = 'mypasswd'
SMTP_SERVER = "smtp.ionos.co.uk:587"
smtpserver = smtplib.SMTP(SMTP_SERVER)
#smtpserver.ehlo()
#smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(FROM_ADDR, PASSWORD)
header = 'To:' + ", " + MAIL_2[0] + '\n' + 'From: ' + FROM_ADDR + '\n' + 'Subject: ' + SUBJECT + '\n'
mmsg = header + '\n' + SUBJECT + '\n' + BODY + '\n\n'
smtpserver.sendmail(FROM_ADDR, MAIL_2,mmsg)
smtpserver.close()
(Sorry but the insert code segment button does not seem to be working)
Note the two lines commented out. I don't know why this works but it does.
You should use f-string for lines 13 and 14

replace these two strings with:
mssg = f"TO:, {MAIL_2[0]}\nFromL {FROM_ADDR}\nSubject: {SUBJECT}\n" \
    f"\n{SUBJECT}\n{BODY}\n\n"
Thanks I was not aware of f-string, just read up on it and it looks really good.