Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email an attachment in R with gmail

Tags:

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.

like image 594
Tyler Rinker Avatar asked Oct 18 '11 04:10

Tyler Rinker


2 Answers

A response that works and works well is found here:
http://r.789695.n4.nabble.com/Email-out-of-R-code-td3530671.html

Thank you to nutterb for an answer from the rhelp list. Thank you to all that tried to assist me and were patient with my ignorance of python.

like image 39
Tyler Rinker Avatar answered Sep 26 '22 21:09

Tyler Rinker


You are running Jython code inside of your R environment, so you're looking for a way to send an attachment using the Jython language, not R.

Since Jython is basically Python, here is a way to send an email with an attachment with Python: How to send email attachments with Python.

You will just have to hack together that code into yours.

like image 157
Blender Avatar answered Sep 25 '22 21:09

Blender