Rails 5应用无法发送SendGrid邮件(Cloud 9与Heroku环境)
It’s frustrating when emails show up in your app logs but never hit the recipient’s inbox—let’s break down the most likely fixes for your issue:
Double-check your API key is actually loading: Even with dotenv, it’s easy to miss a step. Add a quick debug line like
puts ENV['SENDGRID_API_KEY']early in your code to confirm the key is being pulled in correctly. If it returnsnil, make sureDotenv.loadis called before accessing the variable (in Rails this happens automatically, but for standalone scripts you’ll need to explicitly load it).Complete your SendGrid client setup with error handling: Your code snippet cuts off, but the full flow needs to include initializing the client and capturing SendGrid’s official response. Here’s a complete example with debugging built in:
require 'sendgrid-ruby' include SendGrid # Use a verified sender email from your domain (not test@example.com) from = Email.new(email: 'your-verified-sender@yourdomain.com') to = Email.new(email: 'recipient@example.com') subject = 'Test SendGrid Email' content = Content.new(type: 'text/plain', value: 'This is a test email from SendGrid') mail = Mail.new(from, subject, to, content) # Initialize the SendGrid client with your API key sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.mail._('send').post(request_body: mail.to_json) # Print response details to debug exactly what's happening puts "Status Code: #{response.status_code}" puts "Response Body: #{response.body}" puts "Headers: #{response.headers}"
The status code and response body will tell you exactly why SendGrid isn’t sending the email—common issues include invalid API keys, unauthenticated senders, or account-level restrictions.
Check SendGrid’s dashboard for clues: Don’t rely just on your app’s logs. Log into your SendGrid account and check the Email Activity tab—this will show if emails were accepted, dropped, bounced, or marked as spam. The Logs section also has detailed API request records that can pinpoint problems your app’s logs might miss.
Verify your sender domain/email: SendGrid requires sender emails to be authenticated. Go to Settings > Sender Authentication in your dashboard to make sure your domain is verified, or add a single verified sender email if you’re not using domain authentication. Using
test@example.comwon’t work—you need an email from a domain you own and control.Confirm environment variables in production: If this works locally but not after deployment, make sure your hosting platform (Heroku, AWS, etc.) has the
SENDGRID_API_KEYset in its environment variables. Never commit your.envfile to version control, so production needs its own way to access the key.
Give these steps a try, and the response from SendGrid should point you directly to the root cause.
内容的提问来源于stack exchange,提问作者kaspar9

