sending emails with smtplib in python from shared mailbox - python

I am working on script to send emails.
Emails are supposed to be send from a shared mailbox in outlook.
This shared mailbox doesn't have a password and here is the trick: on the one hand I need the authenticate and provide a password, on the other hand I have no password to provide.
I ran the scripted with my professional outlook mailbox (email address + password) and it works.
Here is my config:
MY_ADDRESS = "---emailaddressofthesender---"
PASSWORD = ""
MESSAGE = "some message"
# set up the SMTP server
s = smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
msg = MIMEMultipart() # create a message
# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']="---emailaddresseofthereceiver---"
msg['Subject']="This is TEST"
# add in the message body
msg.attach(MIMEText(MESSAGE, 'plain'))
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
I tried:
Read the doc smtplib. Unless mistaken, I found no mentions about
authentications without password.
PASSWORD = "": authentication error
PASSWORD = None: authentication error
s.login(MY_ADDRESS): PASSWORD argument is missing
remove s.login() method from the script: Client was not authenticated to send anonymous mail during MAIL FROM [PR0P264CA0184.FRAP264.PROD.OUTLOOK.COM]
The only working solution I have now is to send from my mailbox credentials and not from the shared mailbox. For the sake of this project, this solution is not acceptable.
Many thanks in advance for your help

Add this right before the s.send() step and it will work.
s.SentOnBehalfOfName = 'SharedFolder'

Related

How can I send email from python with 2 Factor Authentication?

I have created python file that can send email using less secure apps turned on, but I need it off. How can I send email with 2FA?
# import simple mail transfer protocol library
import smtplib
# import EmailMessage method
from email.message import EmailMessage
contacts = ['<email#email.com>', '<email2#email.com>']
EMAIL_ADDRESS = '<my_gmail>'
EMAIL_PASSWORD = '<my_gmail_password>'
# Create empty Email Message object
msg = EmailMessage()
msg['Subject'] = 'Automated python email sender 5'
msg['From'] = EMAIL_ADDRESS
msg['To'] = contacts
msg.set_content('<sample_content>')
# contact manager we will make sure our connection is closed automatically without us doing it manually
# 465 is the port number for plain SMTP_SSL
# SMTP_SSL means you do not have to use ehlo() ans starttls()
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
What should I add to make 2FA work?
I believe you would need to set up an App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. Learn more
Its basically something thats setup in the users Google account.
Another thing to look at would be Display captcha
if that doesn't work you might need to look into Xoauth2
if you require 2fa
If you want to support 2fa then you should not be using the SMTP server and should be going though the Gmail API and using Oauth2 which will prompt a user to connect via their google account and google will control the 2fa themselves. SMTP servers are not designed to handel 2fa
Try setting up App Password for your Gmail. and used that app password for smtp login.
This will help Set Up APP-Password
Under security you have to generate a password for your application:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('demo#gmail.com', 'password generated by google')
server.sendmail('demo#gmail.com', 'demo#icloud.com', 'Mail sent from program')
print('Mail Sent')
as you can see, you enter your email but instead of typing your own password you enter the password generated by google for your application

Any idea of how to spoof an email sender in python using smtplib?

I was wasting another day of my life messing around with python and I was thinking about how to spoof an email address using smtplib in python. I thought it could be possible to spoof the from address by using the code below but it didn't work. I have seen projects on github that seem to be able to actually spoof the email but if i were to create a program of my own that does this, how exactly would it work? Any ideas? Code:
import smtplib
username = (mygmailusername)
password = (mypassword)
fakefrom = "donaldtrump#gmail.com"
toEmail = (toAddress)
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
server.login(username,password)
server.sendmail(fakefrom,toEmail,"this is the fbi. OPEN UP")
server.close()
Most providers check the account with the sender address, and disallow if the sender address dosn't match with sender. Try if you have a setup box network, to use your provider network smtp server without authentification on smtp 25 port, and most of time the mail can be sent. But with that method, many receiver servers will tag directly this mail as spam/dangerous. You can try that directly in your message tool (outlook,...) it s the same behavior as you code.
Sorry I'm a bit late. The problem, here lies with the second-to-last line:
server.sendmail(fakefrom,toEmail,"this is the fbi. OPEN UP")
You are trying to use the 'fake from' address to actually send the email which isn't what you want to be doing. You just want to 'spoof' it and make the recipient think that the email came from a different address. You do that by defining the sender details in the message body.
The code that you would need to use to make this work would be:
import smtplib
username = (mygmailusername)
password = (mypassword)
fake_from = "donaldtrump#gmail.com"
fake_name = "Donald Trump"
to_email = (toAddress)
to_name = (toName)
subject = "Bonjour"
content = "This is the fbi. OPEN UP"
message = f"From: {fake_name} <{fake_from}>\nTo: {to_name} <{to_email}>\nSubject: {subject}\n\n{content}"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(username, password)
server.sendmail(username, to_email, message.encode())
server.close()

Python smtplib: Unable to send sms messages to phone

I am trying to send messages to my phone using the SMTP protocol. If I log into my Google Account (for which I've enabled less secure apps) I'm able to send a message to '5551234567#tmomail.net'. The subject and body of the email arrive on my phone as a text message.
However, when I try to do the same with Python's smtplib library, I don't get a message. Here's the code I'm using:
import smtplib
# Establish a secure session with gmail's outgoing SMTP server using your gmail account
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
# the account that will send the emails
server.login('me#gmail.com', 'password')
# sendmail(from, to, msg)
server.sendmail('me#gmail.com', '5551234567#tmomail.net', 'hey there!')
Does anyone know what I can do to get the text message to come through from the smtplib? Any suggestions are very welcome!
Try to check the link below.
If seems like you for forgot
server.ehlo()
How to send an email with Gmail as provider using Python?
Please let us know if you see python message in SENT emails folder of Gmail Inbox.
If yes, try to find a differences between one you sent from browser and one you sent from python API.

Gmail blocks login attempt from Python with app specific password

I'm trying to send an email from a Google account using Python's smtplib, but getting an error, and now I'm kind of at a loss. Google responds with the following: Please log in via your web browser and then try again. Learn more at https://support.google.com/mail/answer/78754.
The account has two factor authentication enabled, so I'm using an app specific password for my login. To my understanding, this should then work without enabling the setting for less secure apps, shouldn't it? I've been doing the same with another account while testing without a problem, but now I finally got the credentials for the proper account and there it won't accept the authentication.
I'm aware that there is a Python Gmail API thingy to use with OAuth, but if at all possible I don't want to include more packages and rewrite much, and I don't really want to enable the "less secure apps" setting either.
Is there a way to get this working without either?
If it makes a difference, here is the code I use for sending email. As said before, this was working fine with another account, so I'm not sure if it's actually relevant.
def send_mail(to_address, subject, body):
smtp_user = "myaccount#domain.com"
smtp_password = "MyAppPasswordFromGoogle"
server = "smtp.gmail.com"
port = 587
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = smtp_user
msg["To"] = to_address
msg.attach(MIMEText(body, "html"))
s = smtplib.SMTP(server, port)
s.connect(server, port)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtp_user, smtp_password)
s.sendmail(smtp_user, to_address, msg.as_string())
s.quit()
Edit:
There is an interesting difference between the two accounts: on https://myaccount.google.com/lesssecureapps, my old (working) one says "this setting isn't available for accounts that have two factor authentication enabled", while the new one says "this setting is managed by your domain administrator", even though both use 2FA and it's also forced in both domains. So I suppose there is some setting that the domain admin has to change, but I don't know which one that would be.
I tried to replicate exactly your case (with an account that has a two factor authentication enabled). After creating my app password, I used it in the code.
Anyway, I think your problem is the following:
s = smtplib.SMTP(server, port)
s.connect(server, port)
You execute the connection twice.
Try with
s = smtplib.SMTP()
s.connect(server, port)
or just this
s = smtplib.SMTP(server, port)
The entire code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtp_user = 'myUser#gmail.com'
smtp_password = 'my16charactersAppPassword'
server = 'smtp.gmail.com'
port = 587
msg = MIMEMultipart("alternative")
msg["Subject"] = 'Why,Oh why!'
msg["From"] = smtp_user
msg["To"] = "destinationUser#gmail.com"
msg.attach(MIMEText('\nsent via python', 'plain'))
s = smtplib.SMTP(server, port)
s.ehlo()
s.starttls()
s.login(smtp_user, smtp_password)
s.sendmail(smtp_user, "destinationUser#gmail.com", msg.as_string())
s.quit()
As of now, google will remove the "Allow unsecure apps options" as suggested by other answers till May 30, 2022. Now you would need to generate specific app passwords.
Go to Google Accounts Page
Turn on the 2-step verification.
Security > App passwords
Select "Other apps" from the app menu.
This gives you app password. You could use the same email and this password to login with your python script

Python sending e-mail with SMTP without authentication

I'm making a script that notifies people about some pending tickets in JIRA. These notifications are sent by e-mail, I already got the notification to trigger, but I'm having problems sending the emails.
I can send them using gmail but when I tried to do it with my official account (the one that the company gave me) I am not able to send them. IT guys already provided me the 'localhost' because they use SMTP relays and the port, but they keep telling me that I should start SMTP without authentication, I'm not very sure of how to do this.
The example I found on internet was this:
import smtplib
fromaddr = 'Axel.Sa#mydomain.com'
toaddrs = ['Axel.Sa#mydomain.com']
msg = '''
From: {fromaddr}
To: {toaddr}
Subject: testin'
This is a test
.
'''
msg = msg.format(fromaddr=fromaddr, toaddr=toaddrs[0])
server = smtplib.SMTP('localhost:25')
server.starttls()
server.ehlo("mydomain.com")
server.mail(fromaddr)
server.rcpt(toaddrs[0])
server.data(msg)
server.quit()
But I keep getting this error, If someone can tell me the proper way of sending emails by SMTP without authentication I will be very grateful.
Check this stack:
How to send an email without login to server in Python
change your smtplib.SMTP('localhost:25') to smtplib.SMTP('localhost', 25)

Categories

Resources