Email django from using EmailMultiAlternatives - python

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>"

Related

Django EmailMessgae() Error: MIMEPart.__init__()

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)

Send email to address getting from HTML input via Django

I'm searching for solution to this problem for many hours but can't find anything related. I want to get user's email from input and send mail from admin to that email address. Here are my codes:
views.py:
def index(request):
context = {
'questions': Question.objects.all(),
'applicants': Applicant.objects.filter(status=1),
'empty_cards': range(4 - Applicant.objects.filter(status=1).count())
}
if request.method == "POST":
if request.POST.get('message_text'):
Message.objects.create(
sender_name = request.POST.get('sender_name'),
sender_email = request.POST.get('sender_email'),
message_text = request.POST.get('message_text'))
if request.method == 'POST':
subject = 'Welcome !'
message = 'We will back to you.'
from_email = settings.EMAIL_HOST_USER
recipient_list = 'don't know how to get email'
send_mail(subject, message, from_email, recipient_list)
return render(request, 'index.html', context)
from your code I assume that you already have access to the user's mail
inside the request.
so you can try this:
sender_email = sender_request.POST.get('sender_email')
recipient_list = [sender_email]

How to send a hyperlink in a django send_mail inside html_message

I want to send a hyperlink inside the send_mail in Django , i have set html_message to an anchor but it didn't work , when i am sending an h1 tag it is working fine.
Code:
def sendEmail(request):
email = request.POST.get('email', '')
print(email)
html_message='<h1>Click</h1>'
send_mail(
'Password Recovery',
'Subject',
'boutrosd#hotmail.com',
[email],
html_message=html_message
)
return JsonResponse(0, safe=False)

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.

Why are my html links from django email not clickable?

I sent the following email via Django
subject, from_email, to = 'site Registration', 'support#site.com', self.second_email
text_content = 'Click on link to finish registration'
html_content = '<html><body>Click Here</body></html>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
When I went the the email (google and yahoo email) they both displayed the Click Here text in blue (I assume this means that it's recognized as a link), however, the link is not clickable and does not link to site.com/acc... What am I doing wrong?
Thanks!
You probably need to make it a valid URL: (note the included scheme)
<a href="http://site.com/accounts/user/' + self.slug +'">
I built a helper function to do this, and used render_to_string to use an HTML template to send instead of typing everything out in the function. Here's my function:
def signup_email(username, email, signup_link):
subject, from_email, to = 'Site Registration', settings.DEFAULT_FROM_EMAIL, email
text_content = 'Click on link to finish registration'
html_content = render_to_string('pet/html_email.html', {'username': username, 'signup_link':signup_link})
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
return msg
Then in the views.py just call it:
class OwnerCreateAccount(FormView):
# class based view attributes
def form_valid(self, form):
# other form logic
msg = signup_email(username=username, email=email, signup_link=owner.salt)
msg.send()
return super(OwnerCreateAccount, self).form_valid(form)

Categories

Resources