使用R语言发送邮件报错,已查看指定帮助链接仍未解决,求解决方法
Got it, let's work through this R email problem together. Since the Google support link didn't give you the fix you needed, let's dive into the most common solutions that R users rely on for sending emails via Gmail (and other providers too):
Use an App-Specific Password (Critical for Gmail)
Google no longer allows regular account passwords for third-party apps like R scripts. Here's what to do:- First, enable 2-Step Verification on your Gmail account (this is required to generate an app-specific password).
- Generate a unique app-specific password from your Google Account security settings.
- Replace your regular password in your R code with this new app-specific one.
Example with
sendmailRpackage:library(sendmailR) from <- "<your-gmail-address@gmail.com>" to <- "<recipient@example.com>" subject <- "Test Email from R" body <- "This is a test message sent via R." smtp_config <- list( host.name = "smtp.gmail.com", port = 465, user.name = "your-gmail-address@gmail.com", passwd = "your-app-specific-password", # Use the generated password here ssl = TRUE ) sendmail(from, to, subject, body, control = smtp_config)Verify SMTP Port & Encryption Settings
If port 465 (SSL) isn't working, try port 587 with TLS encryption instead. Adjust your smtp config like this:smtp_config <- list( host.name = "smtp.gmail.com", port = 587, user.name = "your-gmail-address@gmail.com", passwd = "your-app-specific-password", tls = TRUE )This often resolves connection issues caused by network firewalls blocking port 465.
Check for Google Account Login Blocks
Sometimes Google flags R's login attempt as suspicious. Head to your Google Account's Recent Activity page, look for the blocked login from R, and confirm it's a legitimate attempt (click "Yes, that was me").Test Network Connectivity
Make sure your R environment can reach the Gmail SMTP server. Run this command in R to check:system("ping smtp.gmail.com")If you get no response, your network might be blocking access to the SMTP server—reach out to your network admin for help.
Confirm Your R Package Configuration
If you're usingmailRinstead ofsendmailR, double-check your syntax. Here's a working example:library(mailR) send.mail( from = "your-gmail-address@gmail.com", to = "<recipient@example.com>", subject = "Test Email", body = "Hello from R!", smtp = list( host.name = "smtp.gmail.com", port = 465, user.name = "your-gmail-address@gmail.com", passwd = "your-app-specific-password", ssl = TRUE ), authenticate = TRUE, send = TRUE )
If you're still stuck, sharing the exact error message you get from R would help narrow things down even more!
内容的提问来源于stack exchange,提问作者Soumya Boral

