Email an attachment in R with gmail
Asked 07 September, 2021
Viewed 1.4K times
  • 57
Votes

I am desiring to send an email in R with an attachment using gmail. I have found that sendmailR does not work with gmail because it requires authentication (I couldn't get it to work with gmail so I assume this to be true unless someone tells me I'm wrong , in which case I'll post the R output and error message for that). I found a code snippet found here (LINK). As the site suggests the code is not formatted to send attachments but I have got it to send an email. I'd like to extend this code to send attachments (in an email correspondence the author of this code was unable to extend the code to send attachments).

I want to send emails with R using gmail. I am a windows 7 user with the 2.14 beta version of R.

The code that sends emails but not attachments:

require(rJython) 
rJython <- rJython() 
rJython$exec( "import smtplib" ) 
rJython$exec("from email.MIMEText import MIMEText") 
rJython$exec("import email.utils") 

mail<-c( 
#Email settings 
"fromaddr = '[email protected]'", 
"toaddrs  = '[email protected]'", 
"msg = MIMEText('This is the body of the message.')", 
"msg['From'] = email.utils.formataddr(('sender name', fromaddr))", 
"msg['To'] = email.utils.formataddr(('recipient name', toaddrs))", 
"msg['Subject'] = 'Simple test message'", 

#SMTP server credentials 
"username = '[email protected]'", 
"password = 'pw'", 

#Set SMTP server and send email, e.g., google mail SMTP server 
"server = smtplib.SMTP('smtp.gmail.com:587')", 
"server.ehlo()", 
"server.starttls()", 
"server.ehlo()", 
"server.login(username,password)", 
"server.sendmail(fromaddr, toaddrs, msg.as_string())", 
"server.quit()") 

jython.exec(rJython,mail) 

Note this message is cross posted at talkstats.com. I did not receive a reply there (just members telling me they wish they could help). If I receive a workable solution i will also post it there as well.

8 Answer