Django EmailMessgae() Error: MIMEPart.__init__() - python

This is my views file:
I have made a token file to generate a link
and info file for details like EMAIL_HOST_USER and etc.
current_site = get_current_site(request)
email_subject = "Confirm your email #XYZ"
message2 = render_to_string('email_confirmation.html',{
'name': myuser.first_name,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(myuser.pk)),
'token': generate_token.make_token(myuser),
})
email = EmailMessage(
email_subject,
message2,
settings.EMAIL_HOST_USER,
[myuser.email],
)
email.fail_silently=False
email.send()

Had this same issue as well, but, it turned out that I was importing the EmailMessage class.
Instead of doing this:
from email.message import EmailMessage
Use:
from django.core.mail import EmailMessage

EmailMessage(...)[Django-doc] don't have any method named as send_mail() it has to be send() and EmailMessage don't have any attribute named as fail_silently it's a parameter passed to send() method so finally your code will look like this
email = EmailMessage(
email_subject,
message2,
settings.EMAIL_HOST_USER,
[myuser.email],
)
email.content_subtype = "html" # can specify type of your content
email.send(fail_silently=True)

Related

sending a safe html with django emailmessage

Good day, I'm trying to send a html in django email, pls what more can I added to the code.
the email sending is functioning well but it still shows the html tags.
from celery import task
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage
from orders.models import Order
#task
def payment_completed(order_id):
order = Order.objects.get(id=order_id)
subject = f'Testing html sending'
message = render_to_string('orders/order/pdf.html', {'order':order})
email = EmailMessage(
subject,
message,
'youremai#gmail.com',
[order.email, 'youremai#gmail.com']
)
email.content_subtype = 'html'
email.send()
I've tried render_to_string and get_template
same result
You can use EmailMultiAlternatives instead of EmailMessage, and code may look like this
email = EmailMultiAlternatives(
subject,
message_plain_text,
'youremai#gmail.com',
[order.email, 'youremai#gmail.com']
)
email.attach_alternative(message, 'text/html')
email.send()

Django resend activation link, missing 1 required positional argument: 'user'

I have read similar questions but I cannot understand why this is not working. I am trying to send a reactivation email to user when they click on a link. The activation link is generated properly when the user signs up and the email is sent, but when I try to call the same function again to reactivate link, it is not working saying it is missing one parameter. Here's the function:
acounts/views.py
def sendactivationmail(request, user):
# Creating token and masing uid of user
token = default_token_generator.make_token(user)
uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
# Sending email for email verification
subject = 'Please Verify Your Email'
from_email = settings.DEFAULT_FROM_EMAIL
to_email = [user.email]
context = {
'url': settings.BASE_URL + reverse('user-activation-link', kwargs={
'uidb64': uid,
'token': token,
}),
}
contact_message = render_to_string('verify_email.html', context)
plain_message = strip_tags(contact_message)
send_mail(subject, plain_message, from_email, to_email, html_message=contact_message, fail_silently=True)
return redirect(reverse('login'))
accounts/urls.py
from django.conf.urls import url
from .views import *
from . import views
from urllib import request
from django.contrib.auth.models import User
urlpatterns = [
url(r'^reactivate/$', views.sendactivationmail(request, User), name='reactivate'),
Is this the right way to pass on the request and user parameters to the function?
EDIT: This is the link that is used to redirect user:
<p>Click here to resend the activation email.</p>
change your urlpattern to this
urlpatterns = [
url(r'^reactivate/$', views.sendactivationmail, name='reactivate'),
.....
]
and html to, but the user has to be logged in to use this link. remember that
<p>Click here to resend the activation email.</p>

Django 2.1: is it possible to include Ngrok's Domain in an email instead of localhost's?

i am using Ngrok to run my website with https://, and when i send an activation email to myself, instead of seeing 'https://something.ngrok.io/...' i get 'http://localhost:8000/...'.
This is the code responsible for sending the Activation Email which - to my opinion - it should send Ngrok's domain not the development domain ...
...
current_site = get_current_site(request)
mail_subject = 'Activate your customer account.'
message = render_to_string('user_register_email/account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token': user_token.make_token(user),
})
receiver = form.cleaned_data['email']
email = EmailMessage(
mail_subject, message, to=[receiver]
)
email.send()
messages.info(
request, f'An activation link has been sent to %s' % (receiver))
return redirect('accounts:login')
is it possible ?
current_site.domain returns the value set on the site instance, you can either change it from the admin panel, or you can use request.get_host() instead

Django from_email defaulting to recipient

Im using Django, anymail API & mailgun to send emails from my site.
I have a form where users can subscribe,
At present when the email is send to the subscriber's email address, the FROM address default to a combination of their and my email domain.
As an exmample:
User enters test#test.com an receives email from test=test.com#mail.mydomain.com and not the one I specified of info#mydomain.com
I am pretty sure the problem is within my views.py, but im not sure how to resolve.
views.py
def send_email(subject, html_content, text_content=None, from_email=None, recipients=[], attachments=[], bcc=[], cc=[]):
# send email to user with attachment
if not from_email:
from_email = settings.DEFAULT_FROM_EMAIL
if not text_content:
text_content = ''
email = EmailMultiAlternatives(
subject, text_content, from_email, recipients, bcc=bcc, cc=cc
)
email.attach_alternative(html_content, "text/html")
for attachment in attachments:
# Example: email.attach('design.png', img_data, 'image/png')
email.attach(*attachment)
email.send()
def send_mass_mail(data_list):
for data in data_list:
template = data.pop('template')
context = data.pop('context')
html_content = get_rendered_html(template, context)
data.update({'html_content': html_content})
send_email(**data)
# Contact Form - home.html
def HomePage(request, template='home.html'):
form = ContactForm(request.POST or None)
if form.is_valid():
from_email = form.cleaned_data['from_email']
# Create message1 to send to poster
message1 = {
'subject': 'Test',
'from_email': from_email,
'recipients': [from_email],
'template': "marketing/welcome.html",
'context': {
"from_email": from_email,
}
}
# Create message1 to send to website admin
message2 = {
'subject': 'Test - Contact',
'from_email': from_email,
'recipients': ['info#mydomain.com'],
'template': "marketing/admin.html",
'context': {
"from_email": from_email,
}
}
try:
send_mass_mail([message1, message2])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('/thanks/')
context = {
"form": form,
}
return render(request, template, context)
It looks as if you are using the from_email from the user, not info#mydomain.com. In two places you have:
'from_email': from_email,
Many mail providers will limit the addresses that you can send mail from (to stop you sending spam using someone else's address.
Therefore you can't use a from_email that the user gives you. The usual approach is to use your own address as the from_email, but set a reply-to header so that any replies go to the address that the user specified.

Email django from using EmailMultiAlternatives

I'm trying to send a mail using Django with EmailMultiAlternatives. It works well but in "from" says "info"
Is it posible to say my name for example? How can I do this?
Here is my code:
subject, from_email, to = 'Afiliations', 'info#domain.com', 'other#domain.com'
text_content = 'Afiliation is working.'
t = loader.get_template('emails/afiliados.html')
c = Context({ 'order': order_obj })
html_content = t.render(c)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
For the Name to be displayed instead of the username part of the email, just do
from_email = "info#domain.com <info#domain.com>"
OR
from_email = "Name <info#domain.com>"

Categories

Resources