Can API be used to replace SMTP for mail sending in Django especially for things like reset password and mail confirmation.
I will really love if I can get clarification on a topic in django. I am a newbie to django and when it comes to sending mail I register for Mailgun and used the API since I have used requests before but picking up django to work with I am trying to do user registration using DJ-Rest-auth and django_allauth and there is thing about configuring email backend using SMTP.
my question is
Can i do without using SMTP for django_allauth if Yes a workflow how to connect my password reset to use the api for mail.
I can easily pass in the mail function to serve as an alert in the views when user registers
I know I can send mails using django but things like reset password that has a uuid attached to it how can I go about it using API's
def send_simple_message(name, email, phone, course, mode):
""" send mail after successful registration. """
return requests.post(
MAILGUN_BASE_URL,
auth=("api", MAILGUN_KEY),
data={"from": "mail <noreply#mail.com>",
"to": ["mail#cerebrocc.com"],
"subject": "🚨📢New Student Alert🚨📣",
"text": f"name: {name}\nemail: {email}\nphone: {phone} Just registered for {course.title()} class and wants the class {mode}!"})
class RegistrationAPIView(generics.CreateAPIView):
""" The Registration API endpoint for cerebro code camp """
queryset = Registration.objects.all()
serializer_class = RegistrationSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.data['name']
email = serializer.data['email']
phone = serializer.data['phone']
course = serializer.data['course']
mode = serializer.data['mode']
send_simple_message(name, email, phone, course, mode)
return Response(status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
You should not write your plain own mail sending function, you should always use Django's builtin send_mail (or related) function(s), and configure a custom email backend in your settings.
If you need to change how emails are sent you can write your own email backend. The EMAIL_BACKEND setting in your settings file is then the Python import path for your backend class.
https://docs.djangoproject.com/en/3.2/topics/email/#defining-a-custom-email-backend
Django can automatically send various emails in various circumstances, so centralising that configuration so all email sending uses your configured mail sending settings is important, unless you have specific reasons against that.
Given that this is such a pluggable architecture, and both Django and Mailgun are popular, there are existing modules that allow you to send email via Mailgun with such a simple configuration change: https://djangopackages.org/grids/g/email/
Related
Am going to integrate DialogFlow Bot with Hangout integration, I need the username and email whom my chatbot is communicating
You will need to set a a direct API from Hangout from there you can use Data.User to grab what you need
You can see more here
https://developers.google.com/resources/api-libraries/documentation/chat/v1/csharp/latest/classGoogle_1_1Apis_1_1HangoutsChat_1_1v1_1_1Data_1_1Message.html
I have the same requirement but I don't really understand the answer provided here.
In Dialogflow I use the native Hangout Chat integration : https://cloud.google.com/dialogflow/docs/integrations/hangouts
So I suspect that this integration does not send all payload from Hangouts chat to Dialogflow.
Have a look at this:
https://developers.google.com/hangouts/chat/reference/message-formats/events
When user sends a message, or adds the bot or does any event, you can get the name and email. For example in Python it would look like this:
#app.route('/', methods=['POST'])
def on_event():
event = request.get_json()
if event['type'] == 'MESSAGE':
response = event['user']['displayName'])
email = event['user']['email'])
I am trying to use the generic python SMTP lib modules for sending an email from an outlook web application (not office 365) through Python. I am using the right host server name and port no. But still, I am unsure why I am receiving an authentication error. I understand that this is a frequently asked question, but I still wonder why it is unable to authenticate. Any help on this would be appreciated. Thank you.
Our email is configured with a DUO set-up (Two-factor authentication). I initially assumed this might be the reason. But the other methods I used worked perfectly fine without doing any additional setups
Some methods I tried were.
Using Python's win32com.client module in Python for sending email
through Desktop Outlook App.
Using Powershell to send an email
The code is pretty straight forward and simple.
import smtplib
from getpass import getpass
email = '********'
password =getpass("Enter your password")
with smtplib.SMTP('xxxx.xxx.xxx',25) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(email,password)
subject = 'Test'
body = 'Testing email'
msg = f'Subject:{subject}\n\n{body}'
smtp.sendmail(email,email,msg)
It always shows this error, irrespective of the ports I am using.
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Error: authentication failed: authentication failure')
EDIT:
Ok!! so the code absolutely runs fine if I remove the login and prompt password statement. But this seems to be dangerous and I am not sure why it's allowing us to send emails even though we are not logged in. Maybe the Windows Server Active Directory is already registered on the domain
I have a simple CRUD webapp set up in Python/Flask, when one particular function is activated (approving a request) I'd like to send an email notification to the user, but for all I've tried I can't get the email to send through my code.
Here is my config file with all the relevant environment variables set (inside of a Config object):
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT=465
MAIL_USE_SSL=True
MAIL_USERNAME = '**#gmail.com'
MAIL_PASSWORD = '**'
I have also tried calling app.config.update(those values) in my app/init.py file. Here is the current code to do so
mail = Mail()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('./config.py')
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USE_TLS=False,
MAIL_USERNAME = '**#gmail.com',
MAIL_PASSWORD = '**')
mail.init_app(app)
And finally here is the code where I actually attempt to send the email:
msg = Message(html=html, sender='**#gmail.com', subject='Your Reservation for %s' % reservation.item.name, recipients=['**'])
mail.send(msg)
Additionally, it currently fails silently and I don't know how to even view what error is happening. Any help is much appreciated!
My suggestion in the comments was indeed the answer to the question.
Enabling "Less Secure Apps" in the Google Account settings was the necessary step to fix the hangup the OP was experiencing. This link from Google's support page walks you through how to enable this option.
I think, you should switch your sending protocol to TLS
this is sample from my project
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME = '**#gmail.com',
MAIL_PASSWORD = '**'
for me this works very well.
Now that Google is removing the less-secure app access feature due to security reasons, the best way to get around this is to use Sendgrid. They provide 100 free emails per day forever. You can register your same Gmail address as a single sender in SendGrid. Generate an API key and use it in your flask app to send emails.
For reference: Sending Emails from Python Flask Applications With Twilio SendGrid
Is there a way to send the email verification email from my server ?
This is how it's done on the client:
authData.sendEmailVerification().then(function() {
Is there a way to do it on the server ?
firebaser here
To my surprise there currently is no option to send verification email from within the Admin SDK. I'd recommend you file a feature request.
What you can do from the Admin SDK is update a user profile to mark their email as verified. This allows you to take control of the entire verification flow if you want to, finishing with a call to admin.auth().updateUser(...) (on Node.js, see the link for other supported languages).
I just came across the same problem as you. There is a function to generate the verification link using user's email address.
I used this function on an array of email addresses, then load the result to my mail automation API to send mails out. This function is weirdly not documented:
admin.auth().generateEmailVerificationLink([EMAIL_ADDRESS])
You can use :
axios.post('https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=[API_KEY]',
{ requestType: 'VERIFY_EMAIL', idToken: response.data.idToken }
)
https://firebase.google.com/docs/reference/rest/auth#section-send-email-verification
I am beginner with web2py. I have just created a new project.
I want to use a gmail address, let's say g#gmail.com. What do I need to modify ?
mail.settings.server = 'logging' or 'smtp.gmail.com:587' # your SMTP server
mail.settings.sender = 'g#gmail.com' # your email
mail.settings.login = 'g#gmail.com:mypassword' # your credentials or None
Is this OK ?
What is the purpose of 'logging' ?
Should be
mail.settings.server = 'smtp.gmail.com:587'
Setting mail.settings.server = 'logging' has the effects of logging to console requests for sending emails but does not send the emails. It is useful for debugging email problems.