Uzair Nadeem
Uzair Nadeem

Reputation: 745

Send sender name with email SendGrid - Rails

I am using SendGrid to send emails from my application. I want to send sender name along with sender email e.g. from: 'Maxcreet <[email protected]>'

It is working fine using Letter Opener and MailTrap but SendGrid only show sender email.

Here is my SendGrid functionto send emails.

def deliver!(mail)
  email.from = SendGrid::Email.new(email: mail[:from].addrs.first.address)
  email.subject = mail.subject
  email.add_personalization(build_personalization(mail))
  build_content(mail)
  send!(email)
end

I have checked mail[:from] values using puts it gives following values:

puts mail[:from]                      => Maxcreet <[email protected]>
puts mail[:from].addrs                => Maxcreet <[email protected]>
puts mail[:from].addrs.first          => Maxcreet <[email protected]>
puts mail[:from].addrs.first.address  => [email protected]

Above 3 seems OK for me but when I use any of them in

email.from = SendGrid::Email.new(email: mail[:from].addrs.first.address)

It does not sent my email and even I do not find my email in sendgrid dashboard.

Following this also tried email.fromname but this even did not work.

Upvotes: 4

Views: 2706

Answers (2)

jacobmovingfwd
jacobmovingfwd

Reputation: 2273

It looks like you're mixing gems or objects. SendGrid::Email.new just needs a from String, and might support a name String. You're extracting the address from your mail[:from] Hash with mail[:from].addrs.first.address, but you need to provide the name as a distinct Key.

In the SendGrid Ruby gem 'kitchen sink" example, they don't show a name on the From argument, but they do on the personalization.

Try: email.from = SendGrid::Email.new(email: '[email protected]', name: 'Maxcreet'))

or dynamically: email.from = SendGrid::Email.new(email: mail[:from].addrs.first.address, name: mail[:from].addrs.first.name))

if your mail Object recognizes that Key.

Otherwise, you'll need to look at your mail gem's documentation for how to extract a Friendly/Display Name from that mail[:from].addrs Object.

Upvotes: 0

Zia Ul Rehman
Zia Ul Rehman

Reputation: 2264

SendGrid's ruby API has this option with name name and not fromname.

So the following should solve your problem.

email.from = SendGrid::Email.new(
  email: mail[:from].addrs.first.address, 
  name:  mail[:from].addrs.first.name
)

I concluded this by trying it from this doc.

Upvotes: 4

Related Questions