sendgrid-ruby: Unsubscribe tags not working on Transactional Emails

I am able to set a template and asm group id using the following: (it works great, thanks!)

mail = SendGrid::Mail.new do |m| m.to = email_address m.from = "Kudoso" m.subject = ' ' m.html = " " m.text = " " end header = Smtpapi::Header.new header.add_filter('template', 'enable', 1) header.add_filter('template', 'template_id', template_id) header.set_asm_group(group_id) mail.smtpapi = header mail.template = template client.send(mail)

However, the [unsubscribe] and [Unsubscribe_Preferences] tags in the template are not getting wired up. Instead, there is a div placed at the bottom of the email with the proper links. Thoughts?

THANKS so much.

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 43 (17 by maintainers)

Commits related to this issue

Most upvoted comments

I just got a response from SG support on an issue about this. They offered the same solution but gave much more detail. I’ll post it here so people can find it in the future.

The [Unsubscribe] tag as outlined here is specifically used for sending through our Marketing Campaigns platform.

For implementing unsubscribe links into transactional emails sent through the v3 Mail Send API, you would want to configure subscription tracking for us to append unsubscribe links automatically.

If you’re going to be sending through emails via the API using a transactional template (as opposed to external html), there is currently a known issue with Transactional Templates regarding Unsubscribe Substitution tags where the HTML editor encodes the < or > brackets into &lt;, causing Unsubscribe Substitution tags to not get replaced by our system.

The workaround is to set a substitution parameter for a replacement tag within your X-SMTPAPI Header or Personalizations and place that replacement tag in your HTML.

For example, you can set a substitution parameter to replace the tag %Unsubscribe% with the Unsubscribe Substitution tag, <%asm_group_unsubscribe_url%>. You can do the same thing for the raw url Unsubscribe Substitution tag <%asm_group_unsubscribe_raw_url%>, which provides the raw url of the unsubscribe link.

"sub": {
     “%Unsubscribe%”: [“<%asm_group_unsubscribe_url%>"],
     “%rawUnsubscribe%": ["<%asm_group_unsubscribe_raw_url%>"]
}

In your HTML, you’ll want to use the replacement tag %Unsubscribe% within your link.

<a href=“%Unsubscribe%”></a>

If you’re using the %rawUnsubscribe% tag, you can include a custom unsubscribe message, such as Click here to unsubscribe!.

<a href=“%rawUnsubscribe%">Click here to unsubscribe!</a>

Don’t forget to designate the Unsubscribe Group ID asm_group_id in your X-SMTPAPI Header or Personalizations.

Emails that are sent with an Unsubscribe Group specified in the X-SMTPAPI Header but without any unsubscribe substitution tags will have two links at the bottom of the email: an “Unsubscribe” link, and an “Email Preferences” link. If you do not specify an Unsubscribe Group when sending an email, the unsubscribe link will act as a Global Unsubscribe. This means that the recipient will no longer get any emails at all, including potentially important emails like password resets.

Unsubscribe Substitution Tags

When you add the <%asm_group_unsubscribe_url%> tag to your email, we will replace that tag with the text Unsubscribe From This List, wherever the tag is found in your email. This link will allow your recipients to unsubscribe from the unsubscribe group that you attached to this email.

Alternatively, you can use the <%asm_group_unsubscribe_raw_url%> tag which will be replaced with only the group unsubscribe URL without the hyperlinked text “Unsubscribe From This List”.

When you add the <%asm_global_unsubscribe_url%> tag to your email, we will replace that tag with the text Unsubscribe From All Emails, wherever the tag is found in your email. This will allow your recipient to be globally unsubscribed from all of your emails.

When you add the <%asm_preferences_url%> tag to your email, we will replace that tag with the text Manage Email Preferences, wherever the tag is found in your email. This will allow your recipients to see your Unsubscribe Groups in a Subscription Preference page and then choose which groups they are interested in.

Alternatively, you can use the <%asm_preferences_raw_url%> tag which will be replaced with only the Subscription Preference page URL without the hyperlinked text “Manage Email Preferences”.

Unsubscribe Substitution Tags

Here’s a related Node example that is working for me now. The trick was to specify a valid unsubscribe group ID with the request (otherwise <% asm_… %> values would not replace). I think* only one group ID can be specified. In my case though, all default unsubscribe groups were still visible on the email preferences page (cool).

Wish list item: Make <% asm_… %> tags replace in the transactional template itself like it does with marketing templates. ☺️

// settings 
const sendGridWelcomeTemplateID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
const fromEmail = 'an@example.com'

// sendgrid  mail api
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
sgMail.setSubstitutionWrappers('{{', '}}')

// placeholder contact
let contact = {
  email: 'to@email.com',
  firstName: 'Joe',
  lastName: 'Shmoe'
}

// add replacement text/dynamic fields/tags for email content
let substitutions = {
  firstName: contact.firstName,
  lastName: contact.lastName,
  asmGroupUnsubscribeUrl: '<%asm_group_unsubscribe_url%>',
  asmGlobalUnsubscribeUrl: '<%asm_global_unsubscribe_url%>',
  asmPreferencesUrl: '<%asm_preferences_url%>',
  asmPreferencesRawUrl: '<%asm_preferences_raw_url%>'
}

let msg = {
  to: contact.email,
  from: fromEmail,
  subject: 'Welcome!',
  // text: 'Please read this entire email, as it contains very important information.',
  // html: '<strong>Please read this entire email, as it contains very important information.</strong>',
  templateId: sendGridWelcomeTemplateID,
  substitutions: substitutions,
  categories: [
    'administrative', 'welcome'
  ],
  asm: {
    groupId: 1111 
  }
}

sgMail.send([msg])
.then(function (results) {
  console.log('send complete!')
  console.log(results)
})
.catch(function (err) {
  console.log('there was an error sending the welcome email.')
  console.log(err)
})

Here’s a transactional template to test with:

<html>
<head>
<title>Be Awesome Now</title>
</head>
<body>
<p>Hello {{firstName}} {{lastName}},</p>
<p>{{asmGroupUnsubscribeUrll}}</p>
<p>{{asmGlobalUnsubscribeUrl}}</p>
<p>{{asmPreferencesUrl}}</p>
<p>{{asmPreferencesRawUrl}}</p>
</body>
</html>

@rg34 and @thinkingserious , I ended up making it work with the<%asm_group_unsubscribe_raw_url%> and <%asm_preferences_raw_url%> tags.

The problem I was facing was happening because I switched from “CODE” to “DESIGN” before saving the template. When I did that, it changed the < and > for < and > and that change caused the problem.

When I did add the tags and saved the template while still in “CODE” mode, it worked 😄

@rlpacht I did! Here’s what I had to do:

  • In the html tag, <a href="<%asm_group_unsubscribe_raw_url%>">Custom unsubscribe here</a>
  • In the application sending the email, make sure you set the ASM. In Java, I did that like this. (I commented on the Ruby issue by mistake). You have to create an unsubscribe group on the SendGrid web console.
     // From https://app.sendgrid.com/suppressions/advanced_suppression_manager
      if (request.unsubscribeGroup != null) {
        mail.setASM(new ASM());
        mail.asm.setGroupId(request.unsubscribeGroup);
      }
    
  • I also had to turn off what they (now) call the Legacy Email Template. This is in Settings > Mail Settings.

Hope that helps. For the record their support team took a long time to get back to me when I asked about this, by which time I’d already solved the problem.

This is still a problem, anyone have a solution?

I feel like this should be easy but it is painfully difficult

I really struggled to get this problem fixed, running the sender using PHPMailer – trying to understand how this can be done with simple SMTP instead of using the ASM library.

I added both <%asm_group_unsubscribe_raw_url%> and <%asm_group_unsubscribe_url%> and they did nothing to change the unsubscribe link. Finally after enough reading around, I discovered that you needed to also include the asm: {} attribute in the X-SMTPAPI header, with the group ID of the unsubscribe group you generate here: https://app.sendgrid.com/suppressions/advanced_suppression_manager

eg. X-SMTPAPI: {"category": "My email digest", "asm": {"group_id": 123456}}

Or in PHP

$mail = new \PHPMailer;
$mail->addCustomHeader('X-SMTPAPI', '{"category": "My email digest", "asm": {"group_id": 123456}}')

You can send this header with any basic SMTP client (Java, Ruby, etc), no need to use ASM.

It would really have helped if Sendgrid had provided this explanation in the documentation, which I was not able to find anywhere.

Same experience as @sbefort … very very frustrating

Great documentation from @wesdotcool. Too bad I spent hours hunting for it on sendgrid.com before finding it inside a Github issue.

Not sure if this helps for this specific issue, but I was trying to use the replacement tag to place the unsub link at a custom position in our email and couldn’t get it to work. The sent emails were always appending the global ones at the end of the email, which are hard to style. In the end I figured you need to wrap the replacement tag in a link for it to work, as follows: <a href="%your_replacement_tag_value%">Unsubscribe Here</a>

Thanks @gabrielkrell, @adam-ludgate, @wesdotcool. I was stuck on the C# implementation and now the unsubscribe links are finally showing. But they stop working when added in the footer through Mail Settings. I noticed the bug still persists with characters (< and >) being converted to (&lt; and &gt;). So I tried the workaround that @wesdotcool suggested which was to do something like “%rawUnsubscribe%”: [“<%asm_group_unsubscribe_raw_url%>"], but then they show up in the email with the link as <%asm_group_unsubscribe_raw_url%> and does not get the raw URL.

Has anyone gotten it to work with the Mail Setting’s global footer?

Edit: I reached out to SendGrid for support. They do not recommend using the asm tags with the global footer as of this moment. So a fix is to just put the footer manually in all of the email templates.

Hello @logicxd,

Could you please reach out to our support team as they are best suited to help with this type of issue?

Thanks!

With Best Regards,

Elmer

That would be fantastic @owntheweb! Thanks!

Thanks @thinkingserious . As I’m submitting a node example, perhaps here? I’ll give it a shot within 48 hours. 😄

Hi @gabriellet,

Do you mind adding your solution as a PR here?

With Best Regards,

Elmer

After a couple hours of research and testing, I come to this understanding and solution.

The Marketing Campaign UI conveniently gives you access to your contacts’ custom fields and a few other variables as substitution tags while building emails. You can view them in the left pane. Transactional templates do not offer these tags, including [Unsubscribe]. However, You do have access to <%asm_group_unsubscribe_raw_url%> and related tags. But be careful because those tags can cause problems because of the < and >. Sendgrid has fixed this issue by introducing a new code builder mode that does not allow you to switch between design and code, but I still ran into this bug on my own server while attempting to render HTML. The work around I’ve chosen is to add the [Unsubscribe] substitution in manually (you can use a different tag if you like). When sending an email through the api, templated or not, you can add in a substitution like this:

  personalization = Personalization.new
  personalization.to = Email.new(email: 'test1@example.com', name: 'Example User')
  personalization.substitutions = Substitution.new(key: '[Unsubscribe]', value: '<%asm_group_unsubscribe_raw_url%>')
  personalization.substitutions = Substitution.new(key: '[Unsub_All]', value: '<%asm_global_unsubscribe_raw_url%>')
  personalization.substitutions = Substitution.new(key: '[Preferences]', value: '<%asm_preferences_raw_url%>')
  mail.personalizations = personalization

I read this documentation for Marketing Campaigns and was really confused when it didn’t work for other emails. Then I found this github issue and put everything together

Awesome. Sendgrid’s reply was the same. Thanks, @danielweinmann!

@rg34 were you able to fix this? I’m having the same problem here.

For this particular email template, we do not have any substitutions for first_name for instance.