Gmail API Oauth2 Send from different address - python

I am able to send e-mails using Python and the google libraries (googleapiclient, google_auth_oauthlib.flow, and google.auth.transport.requests). I'm trying to get an alternate "from" or "reply-to" address, and it's not working. My code for creating a message is like so:
# Returns an e-mail message suitable for submission through the gmail api.
def create_message(sender, to, subject, message_text):
message = MIMEMultipart()
message['to'] = to
#message['from'] = sender
message['from'] = 'derp#nowhere.com'
message['subject'] = subject
message.attach(MIMEText(message_text, 'html'))
return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
As you can see, I've adjusted the from attribute of the message. When this message is sent, it is from the gmail account owner, not "derp". How do I make the message come from a different address?

Add the e-mail address as whom you want to issue e-mail as a "Send Mail As" account: https://mail.google.com/mail/u/2/#settings/accounts. It is necessary for that other account to verify he has control of that e-mail address.
It appears not to be possible to "spoof" e-mails using gmail oauth without this verification process, though if you use the deprecated "less secure apps", it is still possible.

Related

How to resolve the 'Unable to relay recipient in non-accepted domain' error using smtplib?

I have set up an automation process for a few business critical processes and would like to set up channel notifications in slack. When I send emails to recipients within the business it works fine! However, as soon as I change the email to an external email address (such as a gmail address) I get the error 550, b'5.7.54 SMTP; Unable to relay recipient in non-accepted domain. Does anyone know how to resolve this?
My Code
import smtplib
sender_email = "middleofficenotifications#mycompany.co.nz"
rec_email = ['example#gmail.com']
SUBJECT = "This is a TEST"
TEXT = "Please ignore this test, just seeing if the distribution group gets this message. It is DM setting up notifications for code failing/db issues that need to be handled by MO"
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
server = smtplib.SMTP('outlook.mycompany.co.nz')
server.sendmail(sender_email,rec_email, message)

exchangelib: Sending an email as a distribution list

I'm using the exchangelib python EWS library to send emails. Sending from my mailbox works as expected but how can I send an email from a distribution list I have "Send As" permissions already applied (Have tested in Outlook changing the from address)?
The below code snippet will send the email but "me#domain.com" account shows as the sender. If I change "access_type=DELEGATE" to "access_type=IMPERSONATION", I receive an error "ErrorNonExistentMailbox: The SMTP address has no mailbox associated with it.".
credentials = Credentials("me#domain.com", password)
config = Configuration(server=server, credentials=credentials)
account = Account(primary_smtp_address="distlist#domain.com", config=config, autodiscover=False, access_type=DELEGATE)
message = Message(account=account,subject="subject",folder=None)
message.sender = "distlist#domain.com"
message.to_recipients = "me#domain.com"
message.body = "test"
message.send(save_copy=False, copy_to_folder=False)
Any help or guidance is very much appreciated
A distribution list usually doesn't have its own mailbox in Exchange, so you can't use its email address as primary_smtp_address for the account.
Messages have both a sender and an author field. You could try to set the distribution list email in the author field. Then emails may show up as coming from that email address.

sending emails with smtplib in python from shared mailbox

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'

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.

Emails which are sent by python script drop in Spam on GMail

After registration on our service user is sent by email with confirmation link.
But when it is sent to Gmail or other mail services it usually drops to spam.
Here is the code:
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
def activate_email(self, email=None):
if email: self.email = email
self.is_activated = False
self.activation_code = hashlib.sha256(str(self.email) + os.urandom(256)).hexdigest()[:32]
self.save()
subject = u'Welcome to the {0}!'.format(settings.SITE_NAME)
message = render_to_string('users/emails/activation.html', {'activation_code': self.activation_code, 'site_name': settings.SITE_NAME, 'site_domain': settings.SITE_DOMAIN})
self.email_user(subject, message, settings.SITE_EMAIL)
How to add DKIM or other license to this email in order to make Google trust to our server?
We're using Zimbra mail server on our site domain.
P.S. I found this snippet: https://djangosnippets.org/snippets/1995/
Is it suitable somehow in my case or not?
Thank you!
How your mail is treated depends first and foremost on the configuration of the email server which sends the messages generated by your application, and the DNS records associated with it.
Google's guidelines for bulk senders are a great place to start. Check that your mail server (and the emails themselves) comply with the rules.
DKIM is one of these guidelines, so yes: adding DKIM signatures will help. A few other points in the guide:
"Use the same address in the 'From:' header on every bulk mail you send." If you used different From headers while testing or something, this could be the problem.
Publish an SPF record.
Publish a DMARC policy.

Categories

Resources