I’m having a problem with smptlib, I don’t understand why the code I’m using is not sending the email with a different sender from the one used to login.
For my CS class I have to send an email with a spoofed sender as an assignment for the next lesson.
I started tinkering around and I sent myself an email, using the Gmail smpt server and one of my gmails as the sender.
Everything’s good, except it isn’t, because the sender for some reason is not spoofed (the “From:” field in my email appears to be “myrealgmail” and not “sillyemail”). Here’s the code I used:
import smtplib
def send_email(real_email, fake_sender_email, header, receiver_email, receiver_name, subject, body, password):
# Set up the SMTP server
smtp_server = "mysmptserver" #I'm using Google's SMTP server
smtp_port = 587
# Create the email
msg = f"From: {header} <{fake_sender_email}>nTo: {receiver_name} <{receiver_email}>nSubject: {subject}nn{body}>"
try:
# Connect to the server and send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Secure the connection
server.login(real_email, password)
server.sendmail(real_email, receiver_email, msg.encode())
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email. Error: {e}")
# Example usage
real_email = "myrealgmail"
password = "mypassword"
fake_sender_email = "sillymail"
receiver_name = "Willem Dafoe"
receiver_email = "receivermail"
header = "Silly header"
subject = "Silly subject"
body = """
Silly body
"""
send_email(real_email, fake_sender_email, header, receiver_email, receiver_name, subject, body, password)
I tried to send it to another mail, to check if it was a problem related to the mail I was send it to. Useless.
I tried reformatting it with email.utils.formataddr
. Useless.
I tried reformatting it with email.mime
. Useless.
I came to the conclusion that either I’m doing something wrong or the problem resides in Google’s SMPT server. Perhaps you can’t spoof senders when using their SMPT server, and okay, understandable, but then what am I supposed to do? Most of emails services nowadays don’t support simple “Username” and “Password” logins for security reasons and that’s why I used Google’s server, with the App Password feature it works, but it could also be the cause of this problem.
Am I doing something wrong? If I’m not, is this problem caused by Google’s server? If it is, which SMPT server should I use? Thanks in advance
EDIT: Okay, comments confirmed that Google’s SMTP doesn’t allow a different sender from the one specified. I understand that this is a feature not a bug, what I meant with “problem” is that this is a problem for me, in the specific exercise I’m trying to complete. If someone has another SMTP server to try that would be great, I’ll search it myself for now and post another edit if I find a valid SMTP server for this
3