How to send an email to dynamic email account in Django? - django

I have a contact form in my template, so that when a user requests information about a house users can contact different sellers to request information. I don't know how I can send email to different accounts as you know in the system exist multiple sellers.
This is my contact form :
Where "Nombre" is the name of the user that wants information and "Mail" is the e-mail of the user that wants information.
The seller of the House is who will receive the email.
I can't use that:
EMAIL_HOST_USER =
EMAIL_HOST_PASSWORD =
because not only one person will receive all emails

You can use EmailMultiAlternatives and customize your to list
you can try:
from django.core.mail import EmailMultiAlternatives
def view_where_i_send_email(request):
# some view content
# vars to render into html email template
d = Context({'arg_1': arg_1, 'arg_n' : arg_n,})
# get the template to tge email
template = "emailtemplate.html"
htmly = get_template(template)
# render the template and its content
html_content = htmly.render(d)
subject = "Subject"
from_email = "fromthisemail#domain.com"
# HERE you add the emails to wich you want to send
to = [email1]
to.append(email2)
to.append(email3)
msg = EmailMultiAlternatives(subject, "", from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()

Related

Customize django-otp email template

I'm doing two-factor authentication (2FA) in my Django app and using django-otp package. I want to send my custom email to users. I followed the official documentation and added my custom settings as follow:
# django-otp template
OTP_EMAIL_SUBJECT = _('Please confirm your login attempt')
OTP_EMAIL_BODY_TEMPLATE_PATH = 'account/email/login_confirmation_otp.html'
The above settings are working and it's sending the email in text/plain content type but I want text/html content type.
The following code is sending the email:
def generate_challenge(self, extra_context=None):
"""
Generates a random token and emails it to the user.
:param extra_context: Additional context variables for rendering the
email template.
:type extra_context: dict
"""
self.generate_token(valid_secs=settings.OTP_EMAIL_TOKEN_VALIDITY)
context = {'token': self.token, **(extra_context or {})}
if settings.OTP_EMAIL_BODY_TEMPLATE:
body = Template(settings.OTP_EMAIL_BODY_TEMPLATE).render(Context(context))
else:
body = get_template(settings.OTP_EMAIL_BODY_TEMPLATE_PATH).render(context)
send_mail(settings.OTP_EMAIL_SUBJECT,
body,
settings.OTP_EMAIL_SENDER,
[self.email or self.user.email])
message = "sent by email"
return message
in django_otp/plugins/otp_email/models.py. I want to override generate_challenge() function and add html_message in send_email() function but don't know how to do it?

How to include an avatar/profile image in Django send_email with a "noreply" address?

In email clients such as Gmail and Apple Mail, with each incoming email there's an avatar/profile image of the email's sender.
I have a Django app that sends emails from a "noreply#mycompany.com" email address using send_mail. The (sanitized) code looks something like the following:
from django.template.loader import get_template
from django.core.mail import send_mail
from myapp.models import User
...
users = User.objects.all()
subject = 'Email for {name}'.format(name=user.name)
plaintext = get_template('emails/email_template.txt')
html = get_template('emails/email_template.html')
data = {'name': user.name}
text_content = plaintext.render(data)
html_content = html.render(data)
for user in users:
send_mail(subject, text_content, 'noreply#mycompany.com', [user.email], html_message=html_content)
print('Email sent: ' + user.email)
I want to have my company's logo be displayed in email clients as the avatar/profile image. What is the best way to accomplish this? For example, is this something I can specify in my emails' Django template?

Create an email in django with an HTML body and includes an attachment

Can I send an html formatted document as the body of an email and include an attachment?
send_mail() has an option for html_message but the EmailMessage class does not.
My understanding is that to send an attachment, I need to use the EmailMessage class to use the attach_file method.
Am I missing something? I thought send_mail() uses the EmailMessage class, so why do these two features seem mutually exclusive?
Check out EmailMultiAlternatives it has an attach function that you can use for this purpose.
Here's an example of how to use it:
from django.core.mail import EmailMultiAlternatives
subject = request.POST.get('subject', '')
message = request.POST.get('message', '').encode("utf-8")
# Create an e-mail
email_message = EmailMultiAlternatives(
subject=subject,
body=message,
from_email=conn.username,
to=recipents,
bcc=bcc_recipents, # ['bcc#example.com'],
cc=cc_recipents,
headers = {'Reply-To': request.user.email},
connection = connection
)
email_message.attach_alternative(message, "text/html")
for a in matachments:
email_message.attach(a.name, a.document.read())
email_message.send()
I see that to have an html email, I can have html as the body, but I just need to change the content_subtype to html.
msg_body.content_subtype = "html"
Thanks for your help, it got me back to the right page to read in better detail.

How to send email to settings.MANAGER in django recipient_list

In Django, I wish to have the send_email send the email to settings.MANAGERS and to the ticket issuer as well. So trying to set those in recipient_list porduced no luck. I am using class based view.
# views.py
...
from django.conf import settings
...
class TicketCreate(CreateView):
model = Ticket
fields = ['title', 'question_detail',]
raise_exception = False
success_url = reverse_lazy('ticket_list')
template_name = 'ticket/ticket_form.html'
def form_valid(self, form):
form.instance.owner = self.request.user
send_mail(
subject=form.cleaned_data.get('title').strip(),
message=form.cleaned_data.get('question_detail'),
from_email=form.cleaned_data.get('request.user.email'),
recipient_list=['settings.MANAGERS','request.user.email',],
)
return super(TicketCreate, self).form_valid(form)
# settings.py
...
MANAGERS = [
('Manager', 'email_id#somedomain.com'),
]
What would be the solution to achieve this?
MANAGERS is a tuple, and only the second element in each tuple is relevant. This will work:
sender = form.cleaned_data.get('request.user.email')
recipients = [a[1] for a in settings.MANAGERS]
recipients.append(sender)
send_mail(
subject=form.cleaned_data.get('title').strip(),
message=form.cleaned_data.get('question_detail'),
from_email=sender,
recipient_list=recipients,
)
The mail_managers function does most of this for you - the only difference being that it doesn't let you control the sender email (it uses SERVER_EMAIL).
Note that you should be very careful about sending mail on behalf of other people - it is only recommended if you control the sender's domain. Otherwise your messages have a good chance of being caught as spam, with the associated reputation risk for the sending server.
Thanks solarissmoke, Because I only let logged in users send the ticket and that all users are required to authenticate with valid email address, I assume users do NOT need to enter email addres again. So, get email from the user data and insert that into the ticket.
Therefore, I modified a bit like below and all work just cool now. Thanks again and you are right about spam stuff - all under my control.
sender=self.request.user.email
recipients = [a[1] for a in settings.MANAGERS]
recipients.append(sender)
send_mail(
subject=form.cleaned_data.get('title').strip(),
message=form.cleaned_data.get('question_detail'),
from_email=sender,
recipient_list=recipients,
)

Send mass mail with hidden recipients

I have a functionality in a Django app to send an email to all the registered users, I'm currently doing it with 'EmailMessage' and it works perfectly but everybody gets to see every other recipient's email which is unwanted.
Is there a way to hide recipients using the Django mailing functions?
Thank you.
when you instantiate EmailMessage class you can provide bcc attribute such as the example.
Here is the EmailMessage class
class EmailMessage(object):
"""
A container for email information.
"""
content_subtype = 'plain'
mixed_subtype = 'mixed'
encoding = None # None => use settings default
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, cc=None):
so if you provide bcc recipient with the attribute name. you can set the target email as bcc recipient.
message = EmailMessage('hello', 'body', bcc=['user#email.com',])
message.send()
http://en.wikipedia.org/wiki/Blind_carbon_copy
https://docs.djangoproject.com/en/1.7/topics/email/
Definitely BCC each address, this should hide them for any recipient. By the looks of the docs you will need to create your own EmailMessage rather than using the predefined wrappers.
You can try this code format if you want to send Mass Email using send_mass_mail() function.
from django.core.mail import send_mass_mail
subject = 'test subject'
message = 'test message'
from_email = 'from#from.com'
recipient_list = ['a#a.com', 'b#b.com', 'c#c.com']
messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list]
send_mass_mail(messages)