Why are my html links from django email not clickable? - python

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)

Related

Django - how to get email links to work on mobile?

My Django site sends out an email confirmation link, and everything seems to work fine on desktop. On mobile devices, however, the link text is highlighted blue and underlined (i.e. it looks like a link) but nothing happens when the user clicks it. It should open a browser tab and say, "you have confirmed your email, etc"
Thanks for any tips!
views.py:
def signup(request):
if request.method == 'POST':
#send signup form
email_address = request.POST['email']
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.get(email=email_address)
return render(request, 'accounts/signup.html', {'error': "Email already in use."})
except User.DoesNotExist:
user = User.objects.create_user(request.POST['email'], password=request.POST['password1'])
#auth.login(request, user)
#send email confirmation link then redirect:
#user = User.objects.get(email=email_address)
current_site = get_current_site(request)
mail_subject = 'Welcome to My Site'
plain_msg = 'Thank you for signing up to My Site! Click this link to activate your account:\n\n'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/'
msg = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>title</title></head><body>Confirm your email address to continue:<br/>Confirm my email address</body></html>'
print(msg)
send_mail(mail_subject, plain_msg, 'my_email#gmail.com', [email_address], html_message=msg)
return render(request, 'accounts/activation-link-sent.html', {'email': email_address})
#truncated for Stack Overflow post
You should use build_absolute_uri to create fully qualified links that include the current domain and protocol, then use this link in your email
link = request.build_absolute_uri('/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/')
Do you have a url pattern that matches this URL? You should consider using reverse for building URLs
path = reverse('activate', kwargs={
'pk': user.pk,
'token': account_activation_token.make_token(user)
})
link = request.build_absolute_uri(path)

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.

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