Automatically send emails using an Alias - gmail

I'm creating an app that automatically sends emails to different users of a Google Group, where the email sender is the Google Group address.
The app is written in Python and is using Mandrill to send the emails. The distribution of the emails is working properly, but I need to sender email to be the Google Group. I have it setup as an alias on my Gmail, which allows me to manually select the alias and send emails from the Google Groups address. I am looking for a way to automatically send the emails from the alias without me having to manually send it from Gmail.

Here is code example how to send email via SMTP by using python. You can configure "From" field so it will be used as sender. Please pay attention there are python libraries being used: smtplib, os and email.
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart('alternative')
msg['Subject'] = "Hello from Mandrill, Python style!"
msg['From'] = "John Doe <john#doe.com>" # Your from name and email address
msg['To'] = "recipient#example.com"
text = "Mandrill speaks plaintext"
part1 = MIMEText(text, 'plain')
html = "<em>Mandrill speaks <strong>HTML</strong></em>"
part2 = MIMEText(html, 'html')
username = os.environ['MANDRILL_USERNAME']
password = os.environ['MANDRILL_PASSWORD']
msg.attach(part1)
msg.attach(part2)
s = smtplib.SMTP('smtp.mandrillapp.com', 587)
s.login(username, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
For more information check this link How to Send via SMTP with Popular Programming Languages?

You can try using the Users.settings.sendAs resource.
Settings associated with a send-as alias, which can be either the
primary login address associated with the account or a custom "from"
address. Send-as aliases correspond to the "Send Mail As" feature in
the web interface.
{
"sendAsEmail": string,
"displayName": string,
"replyToAddress": string,
"signature": string,
"isPrimary": boolean,
"isDefault": boolean,
"treatAsAlias": boolean,
"smtpMsa": {
"host": string,
"port": integer,
"username": string,
"password": string,
"securityMode": string
},
"verificationStatus": string
}
The sendAsEmail property of this resource stands for the email address that appears in the "From:" header for mail sent using this alias. This is read-only for all operations except create.
For other information about managing aliases, you can check out this documentation.

Related

authentication error trying to send Outlook email from Python

I'm testing out a simple script to send an Outlook email from Python 3 (using Spyder).
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = 'my_username#my_company.com'
password = 'my_password'
mail_from = username
mail_to = username
mail_subject = "Test Subject"
mail_body = "This is a test message"
mimemsg = MIMEMultipart()
mimemsg['From']=mail_from
mimemsg['To']=mail_to
mimemsg['Subject']=mail_subject
mimemsg.attach(MIMEText(mail_body, 'plain'))
try:
connection = smtplib.SMTP(host='smtp.office365.com', port=587)
connection.starttls()
connection.login(username,password)
except Exception as e:
print('Got error here')
print(e)
And the output is:
Got error here
(535, b'Authentication unsuccessful, the user credentials were incorrect. [SOME_VALUE_HERE.hostname.prod.outlook.com]')
I know for sure my own username and email are correct - I verified by checking my username's properties > SMTP value. And anyway it's the username I use to login to Windows.
I'm also using the same password for logging into Windows.
Is it possible my company uses different values for host or port? Or on the backend it sends a different user name to the SMTP server?
The error indicates that SMTP authentication is disabled. Read more about that on the page at https://aka.ms/smtp_auth_disabled. The link explains how to enable SMTP AUTH for the whole organization or only for some mailboxes.
Also take a look at the following settings that would block Legacy Authentication:

Unable to set X-SES-CONFIGURATION-SET headers in aws ses

I am using this script to send email using AWS SES and I am able to receive email in my inbox but I am not able to see X-SES-CONFIGURATION-SET header in the received email. I also tried using Simple email body type with ConfigurationSetName still no luck. Any help is highly appreciated.
import boto3
from botocore.exceptions import ClientError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Replace sender#example.com with your "From" address.
# This address must be verified with Amazon SES.
SENDER = "Niranj Raja <niranj#xxx.com>"
# Replace recipient#example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = "niranj#xxx.com"
# Specify a configuration set. If you do not want to use a configuration
# set, comment the following variable, and the
# ConfigurationSetName=CONFIGURATION_SET argument below.
CONFIGURATION_SET = "test-me"
# The subject line for the email.
SUBJECT = "Amazon SES Test (SDK for Python)"
# The email body for recipients with non-HTML email clients.
BODY_TEXT = ("Amazon SES Test (Python)\r\n"
"This email was sent with Amazon SES using the "
"AWS SDK for Python (Boto)."
)
# The HTML body of the email.
BODY_HTML = """<html>
<head></head>
<body>
<h1>Amazon SES Test (SDK for Python)</h1>
<p>This email was sent with
<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the
<a href='https://aws.amazon.com/sdk-for-python/'>
AWS SDK for Python (Boto)</a>.</p>
</body>
</html>
"""
# The character encoding for the email.
CHARSET = "UTF-8"
msg = MIMEMultipart('mixed')
# Add subject, from and to lines.
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = RECIPIENT
#msg['X-SES-CONFIGURATION-SET'] = CONFIGURATION_SET
msg.add_header('X-SES-CONFIGURATION-SET', CONFIGURATION_SET)
print(dir(msg))
print('')
# Create a multipart/alternative child container.
msg_body = MIMEMultipart('alternative')
print(dir(msg_body))
# Encode the text and HTML content and set the character encoding. This step is
# necessary if you're sending a message with characters outside the ASCII range.
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)
msg_body.attach(textpart)
msg_body.attach(htmlpart)
# Create a new SES resource and specify a region.
client = boto3.client(
'sesv2',
aws_access_key_id='test',
aws_secret_access_key='test1',
region_name='region-10'
)
# Try to send the email.
try:
# Provide the contents of the email.
response = client.send_email(
FromEmailAddress=SENDER,
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Content={
'Raw': {
'Data': msg_body.as_string()
}
}
)
print(response)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])

Server.sendmail() sets my recipient as a BCC

I am trying to send an email to a specific recipient using python, but my code keeps setting the recipient as a BCC. How do I change this to set it as a normal To?
Thanks!
Here is my code
import smtplib
def send_email(subject, msg):
login = "My_email"
password = "password"
reciever = "recipient#gmail.com"
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(login, password)
message = 'Subject: {}\n\n{}'.format(subject, msg)
server.sendmail(login, reciever, message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
subject = "Test email"
Sensor_Message = "This has worked"
send_email(subject, Sensor_Message)
I don't know python, but here is what I think the problem is: your message does not contain a To: or Cc: email header containing the recipient's email address.
Because the recipient's email address is in the list of RCPT TO commands sent over SMTP, but not in the email headers, the recipient's MUA (e.g. Gmail, Outlook, Thunderbird, etc.) treats it as a Bcc.
To fix this problem, make sure that the message contains a To: or Cc: header for the recipient.
Unrelated nitpick: the correct spelling is "receiver"
Good luck!

How to fix SMTPNotSupportedError and SMTPAuthenticationError?

I want to send thousands of emails in python by using an open source SMTP server. I have to locally install an open source SMTP server on windows 10 that can send bulk emails , without any limit.
I have installed HMailServer on my windows 10 & configured it as a localhost, I have set a domain as "st.com" in HmailServer and created a account with that domain as "ammar#st.com". Now I have to send emails to user with that account. The list of Receivers emails are in .xlsx file (receivers email e.g. is like ammar#gmail.com)
import pandas as pd
import smtplib
SenderAddress = "ammar#st.com"
password = "123456789"
e = pd.read_excel("Email.xlsx")
emails = e['Emails'].values
server = smtplib.SMTP("localhost", 25)
#server.starttls()
#server.login(SenderAddress, password)
msg = "Hello this is a email form python"
subject = "Hello world"
body = "Subject: {}\n\n{}".format(subject,msg)
for email in emails:
server.sendmail(SenderAddress, email, body)
print("Sent")
server.quit()
After I run this program it gives "SMTPNotSupportedError: STARTTLS extension not supported by server." error and "SMTPAuthenticationError: (530, b'A SSL/TLS-connection is required for authentication.')".
Can anybody tell me how it works that I can send a email to list of users with HmailServer or any other server locally.

How to send an email without login to server in Python

I want to send an email without login to server in Python. I am using Python 3.6.
I tried some code but received an error. Here is my Code :
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer)
server.set_debuglevel(1)
server.sendmail(fromAddr, toAddr, text)
server.quit()
I expect the mail should be sent without asking user id and password but getting an error :
"smtplib.SMTPSenderRefused: (530, b'5.7.1 Client was not authenticated', 'from#Address.com')"
I am using like this. It's work to me in my private SMTP server.
import smtplib
host = "server.smtp.com"
server = smtplib.SMTP(host)
FROM = "testpython#test.com"
TO = "bla#test.com"
MSG = "Subject: Test email python\n\nBody of your message!"
server.sendmail(FROM, TO, MSG)
server.quit()
print ("Email Send")
import win32com.client as win32
outlook=win32.Dispatch('outlook.application')
mail=outlook.CreateItem(0)
mail.To='To address'
mail.Subject='Message subject'
mail.Body='Message body'
mail.HTMLBody='<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment="Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
The code below worked for me.
First, I opened/enabled Port 25 through Network Team and used it in the program.
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer,25)
server.ehlo()
server.starttls()
server.sendmail(fromAddr, toAddr, text)
server.quit()
First, you have to have a SMTP server to send an email. When you don't have one, usually outlook's server is used. But outlook only accepts authenticated users, so if you don't want to login into the server, you have to pick a server that doesn't need authentication.
A second approach is to setup an internal SMTP server. After you setup the internal SMTP server, you can use the "localhost" as the server to send the email. Like this:
import smtplib
receiver = 'someonesEmail#hisDomain.com'
sender = 'yourEmail#yourDomain.com'
smtp = smtplib.SMTP('localhost')
subject = 'test'
body = 'testing plain text message'
msg = 'subject: ' + subject + ' \n\n' + body
smtp.sendmail('sender', receiver, msg)

Resources