send the emails using my gmail account in python? - python-3.x

I m trying to send emails to my users through my Gmail account but it does not work although my Gmail login credentials are also correct but it gives an error
Here is the code for Email Sending!
if request.method == 'POST':
EmailAddress = request.form['Emails']
Subject = request.form['Subject']
Message = request.form['Message']
EmailList = EmailAddress.split(',')
Message = 'Subject: {}\n\n{}'.format(Subject, Message)
for EmailName in EmailList:
Server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
Server.ehlo()
Server.login(UserEmail, UserPassword)
Server.sendmail(UserEmail, EmailName.strip(), Message)
response = "Success"
Server.quit()
Error:-(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t21sm2044741ejr.68 - gsmtp')

Related

sending mail works with mailtrap but not with an outlook server or other

I made a contact form, I tested with the mailtrap service and it works I receive the messages well.
But when I put the smpt parameters for a real mail account I have this error message
SMTPRecipientsRefused at /contact/
{'info#mysite.net': (550, b'relay not permitted: you must be authenticated to send messages')}
the smtp server and the mail account is on the host alwasdata.net, but I tested with an outloock account it's the same thing always this same error. it seems to come from the line in the contact method:
message,
'info#mysite.net',
['info#othersite.net'],
fail_silently=False,
in settings.py i have this config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = "info#mysite.net"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST = 'smtp-blablabla.net'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
in a views.py
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = "Message d'un visiteur sur votre site"
body = {
'Nom': form.cleaned_data['first_name'],
'Tel': form.cleaned_data['tel'],
'Email': form.cleaned_data['email'],
'Message':form.cleaned_data['message'],
}
message = "\n".join(body.values())
try:
send_mail(
subject,
message,
'info#mysite.net',
['info#othersite.net'],
fail_silently=False,
)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('/')
form = ContactForm()
return render(request,'pages/email_form.html',{'form':form})
the forms.py
from django import forms
class ContactForm(forms.Form):
first_name = forms.CharField(max_length=100, required=True)
tel = forms.CharField(max_length=15, required=True)
email = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea, required=True)
I changed a few parameters:
I put all the email addresses on the servers where my site is hosted,
try:
send_mail(
subject,
message,
'info#mysite.net',
['info#mysite.net'],
fail_silently=False,
)
and at my host I changed the parameters of the mail server so that it redirects to the email address that I was targeting. Now it's work

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!

O365 smtp as relay implementation

I am using the below lines of code to send an email but I get the error as 'smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful' . This must be due to MFA. what can I do to authenticate?
import smtplib, ssl
port = 587 # For starttls
smtp_server = "smtp.office365.com"
sender_email = "myemail#companycom"
receiver_email = "myemail#companycom"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
The solution to this issue is to manage the app password in your account or request for service accounts to your admin which doesn't have MFA.

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)

Not able to send the mail without password authentication in python

I am not able to send the mail without password authentication in python.Its printing the last message but mail is not sent.Below is the code that i am using.Anyone please help i am stuck because of this. Thanks in advance.
import smtplib
fromaddr = 'xyz#gmail.com'
toaddrs = ['abc#gmail.com']
msg = '''
From: {fromaddr}
To: {toaddr}
Subject: 'testing'
This is a test
.
'''
msg = msg.format(fromaddr =fromaddr, toaddr = toaddrs[0])
server = smtplib.SMTP("gmail-smtp-in.l.google.com:25")
server.starttls()
server.ehlo("example.com")
server.mail(fromaddr)
server.rcpt(toaddrs[0])
server.data(msg)
server.quit/close()
print("mail sent")

Resources