Django Send emails to all users in the database table - python

I have started django building my first app tutorials, i have to send email to all my users store in the database table on some special Ocations. i have searched on google and found many apis but found it very hard to configure with my app.
here is my model.py
class Users(models.Model):
UserID = models.IntegerField(verbose_name='User ID',max_length=255,primary_key=True)
UserName = models.CharField(verbose_name='User Name',max_length=254,null=True,blank=True)
Email = models.EmailField(verbose_name='Email',max_length=254,null=True,blank=True)
Phone = models.CharField(verbose_name='Phone Number',max_length=254,null=True,blank=True)
i want to have a function here which should get all users one-by-one and send email also tells the status weather the email has been sent or not.

battery's answer is ok, but i would do this way:
recievers = []
for user in Users.objects.all():
recievers.append(user.email)
send_mail(subject, message, from_email, recievers)
this way, you will open only once connection to mail server rather than opening for each email.

Sending email is very simple.
For your Users model this would be:
for user in Users.objects.all():
send_mail(subject, message, from_email,
user.Email)
Checkout Django's Documentation on send emails for more details.
Would be useful if you mention what problem you are facing if you've tried this.
Also note, IntegerField does not have a max_length argument.

for user in Users.objects.all():
send_mail(subject, message, from_email,
user.Email)
This is the best solutions and it works well

Related

Django Display latest emails to certain user in Template

My django app I have created relies heavily on emails that are sent like this:
from django.core.mail import send_mail
send_mail(
'Subject here',
'Here is the message.',
'from#example.com',
['to#example.com'],
fail_silently=False,
)
Lets say that I keep sending an email to an user's email like this:
post = get_object_or_404(Post, pk=pk)
post_title = post.title
author_of_post = post.author
post_email = author_of_post.email
send_mail(
'An User Comment on Your Post',
'''Dear User, ''' '''
Your post, ''' + post_title + ''' was comment on by an user. Want to reply and check it out?
--From the People at Site'''
,
'randomemailuser#domain.com',
[post_email],
)
Now I want to add a notifications area, where it will display all the latest emails sent to the user, in the example of above post_email. So how would I do this. To sum up, I want to have a template where an user can see the latest emails sent to their account, sort of like a notification area. Thanks.
If you want to keep track of the emails that you are sending, you will need to save this information in your database, which means introducing a model. Something like this should do the trick:
#models.py
class SentEmail(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
email_subject = models.CharField(max_length=255)
...
You can obviously attach any additional info onto this model that you want (time sent, email body etc.). Then when you send an email, you'll also want to save a model instance, e.g:
from .models import SentEmail
...
send_mail( ... ) # all the stuff you had before
SentEmail.objects.create(
email_subject="An User Comment on Your Post"
user=whoever_the_user_is
)
Then you just create a view and template to display this information the same way you would any other view.
An alternative approach
Some third party services allow you to manage all transactional emails (sendgrid, mailgun etc.), and they may provide an API for you to fetch all emails sent to a particular user. This would allow you to achieve the kind of thing you described above, but to be honest, I think the approach I suggested above would be alot simpler.

How can I update the email address using the confirmation code in Django?

I use all the functionalities of dj-rest-auth to register, log in, confirm the email address, change the password, reset the password and many more. Unfortunately, the library does not support changing the email address. I would like the authenticated user to first enter the account password and the new email address. After the successful process of authentication, I would like to send the user a specially generated confirmation code. Only when he enters it, the old email address will be changed to the new one. As far as I know, there is no such functionality in dj-rest-auth. Unfortunately, I also have not found any current solutions or libraries for this purpose anywhere. Did anyone have such a problem and could share his solution here? Thank you in advance.
Though i don't have any solution for what you want accurately but here is a replace.
You can use django all-auth and some email backend to send an email to the new added email to confirm the new email. In the sent email, there will be a confirmation link and the user has to click that to confirm the new email.
After using django all-auth you only have to add an email backend which will help in sending email. Rest will be maintained by all-auth.
e.g,
In your settings.py you can add an SMTP email backend to send email from your selected gmail account.
Add these lines of code to your settings.py;
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = DEFAULT_FROM_EMAIL = 'HOST_EMAIL' #HOST_EMAIL is your email from which you want to send email to the user.
EMAIL_HOST_PASSWORD = 'HOST_PASSWORD' #HOST_PASSWORD is the password of the email you are using as HOST_EMAIL
But after doing all these things, to make it work locally, you need to go to your google account which you are using as HOST_EMAIL. Go to manage google account >> security >> Turn on less secure apps. Then you will be able to send email to the user.
NOTE: If you have 2-factor authentication turned on for your google account, then these steps will not work. That type of account has some different setup.

Django contact form which sends email

I have a question regarding creating contact form.
From what I understand when someone sends it I automatically receive an email that I put in the settings. Can a reversed thing be done? I mean when someone fills the form all the information go from one email account to another. For example: user fills the title and message in the form, sends it and then that message goes from one set e-mail address (for example gmail) and then to another e-mail address (for example Outlook).
I want to do that because my client doesn't want to give me the password to his e-mail. So I have to create my own e-mail on gmail and use it to send to client's e-mail.
Assuming you can negotiate adjusting client's mailbox settings you could:
Prefix/suffix subjects of emails sent via the form, e.g.
form = ContactForm(request.POST)
if form.is_valid():
subject = "[WebForm]: " + form.cleaned_data['subject']
Selectively forward prefixed messages to desired e-mail address. See this video for how it's done in Gmail.

flask-user registration: add one more mail id

I am using flask-user package for user registration. Once the user clicks on register, by default it will send an email to the users' email. I want to add admin email along with that. Is it possible to customize it?
I found this but I am not sure how to proceed with that.
Any help would be great.
After taking help of my colleague, I figured out that this can be done by listening to 'signals' sent by the application. For example:
#user_registered.connect_via(app)
def after_user_registered(sender, user, **kwargs):
msg = Message(subject="A new user registered",
body='Some message',
recipients=["admin#example.com"])
mail.send(msg)
PS: This I wanted to implement so that admin can get an email whenever a new user is registered. Hope this helps someone :)

Who is treated as administrator of GAE application?

In accordance with GAE quotas, I can send up to 5000 mails to administrator of the app. But who is treated as administrator? The according Permissions page in the Administration section of GAE console has three users defined:
admin#mydomain.com with role Developer
me#gmail.com with role Owner
somebodyelse#gmail.com with role Viewer
Who is app administrator? First two, all of them or just the second one?
There is a similar question, but it doesn't cover email sending part.
Admin emails get sent to all users who are defined in the project permissions, there is no way to be selective.
To send the emails use the AdminEmailMessage class from google.appengine.api.mail, if you use EmailMessage, then they will come off of your 100 free Recipients Emailed quota, rather than the 3,492,979 Admins Emailed quota.
Example:
Include this import at the top of your script:
from google.appengine.api.mail import AdminEmailMessage
Then use this syntax to send the admin emails.
AdminEmailMessage(
sender = "your#adminaccount.com",
subject = "Hello Admin",
body = "A test admin email"
).send()
This will send an email to all users defined in the projects permissions.
They will then come off of your Admins Emailed quota, rather than your Recipients Emailed quota, as they would if you used the EmailMessage class.
You can use any of these fields, apart from to, cc & bcc.

Categories

Resources