Skip to content

How can I add a from_name? #552

Description

@MadReal

Issue Summary

I can't figure out how to properly add a from name using the mail helper, so that receiver sees the name as well along with the "from Email"

def send_email(to: str, subject: str, template_name: str, template_data: dict, from_email: str = None):
    # api key
    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
    # from
    from_email = Email(from_email if from_email else 'no-reply@clickandrap.com')
    # to
    to_email = Email(to)
    # render the html to replace the dynamic data
    rendered = render_to_string(f'sendgrid/{template_name}', template_data)
    # content type
    content = Content('text/html', rendered)
    # email object
    mail = Mail(from_email, subject, to_email, content)
    # response from send grid
    response = sg.client.mail.send.post(request_body=mail.get())
    # return
    return HttpResponse(response.body)

I tried
from_name = 'My Name' as well as fromname and than added that in mail = Mail(from_email, from_name, subject, to_email, content) but it didn't work.

As well as, still getting errors and the email isn't sending.

def send_email(to: str, subject: str, template_name: str, template_data: dict, from_email: str = None):
    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
    data = {
        "personalizations": [
            {
                "to": [
                    {
                        "email": "clickandrap@gmail.com",
                        "name": "John Doe"
                    }
                ],
                "subject": subject
            }
        ],
        "from": {
            "email": "sam.smith@example.com",
            "name": "Sam Smith"
        },
        "reply_to": {
            "email": "sam.smith@example.com",
            "name": "Sam Smith"
        },
        "subject": "Hello, World!",
        "content": [
            {
                "type": "text/html",
                "value": render_to_string(f'sendgrid/{template_name}', template_data)
            }
        ]
    }
    response = sg.client.mail.send.post(request_body=data)
    # return
    return HttpResponse(response.body)

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: help wantedrequesting help from the communitytype: questionquestion directed at the library

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions