Search code examples
djangodjango-settingsdjango-mailer

Using two different email fo sending eemail in Django


I want to use two email, one for verifying the email and other for sending normal informative emails. I am able to send email for verification with the following code and I want to use my another email for that second perpose.

views.py

    current_site = get_current_site(request)
    subject = 'Welcome to MySite! Confirm Your email.'
    htmly     = get_template('account_activation_email.html')

    d = { 'user': user, 'domain':current_site.domain, 'uemail':urlsafe_base64_encode(force_bytes(user.email)), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user)}

    text_content = ""
    html_content = htmly.render(d)
    msg = EmailMultiAlternatives(subject, text_content, '', [user.email])
    msg.attach_alternative(html_content, "text/html")
    try:
        msg.send()
    except BadHeaderError:
        print("Error while sending email!")
    user.save()

and in settings:

EMAIL_USE_TLS = True
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_HOST_USER = [email protected]
EMAIL_HOST_PASSWORD = 'randompass'
EMAIL_PORT = config('EMAIL_PORT')
DEFAULT_FROM_EMAIL = 'MySte Verification <[email protected]>'

Please help!!!


Solution

  • If you want a different email to be send as "To email", just add the different email in the param. More information here Django Email.

    If you want a different email server that sends the emails, consider making your own email backend that based on specific methods/functions/params uses that specific email server you're looking for. For example:

    from django.core.mail import get_connection, send_mail
    from django.core.mail.message import EmailMessage
    
    with get_connection(
        host=my_host, 
        port=my_port, 
        username=my_username, 
        password=my_password, 
        use_tls=my_use_tls
    ) as connection:
        EmailMessage(subject1, body1, from1, [to1],
                     connection=connection).send()
    

    Hope this helps :)