Following the directions provided in this related question, I was able to send html formated mail messages. Now the question is this: How should I modify the following code, in order to attach one or more files (of any type) to this message?
library(sendmailR)
from <- "<sendmailR@myserver.mycompany.com>"
to <- c("<someone@mycompany.com>","<anotherone@mycompany.com>")
subject <- iconv("Message Title", to = "utf8")
msg <- "<hr size='2' width='33%' style='text-align: left;'><font size='2'>
<i>This email was sent automatically using <a href='http://finzi.psych.upenn.edu/R/library/sendmailR/html/00Index.html' rel='nofollow' target='_blank'>sendmailR</a>.<br>
Please do not reply directly to this e-mail.</i></font>"
msg <- iconv(msg, to = "utf8")
sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))
A working (for me at least) function:
Can be used like this:
Be warned that message sent by this example will probably be marked as spam, since it is a short text and a big picture -- nevertheless for larger messages and, let's say, pdf attachments it should go through. If not, you may consider adding also a text version of the message.
EDIT (less relevant now): The most deep insight on how to make MIME messages can be found here.
With the mailR package (https://github.com/rpremraj/mailR), you could send HTML emails and additionally attach files with ease as below:
Edit (2014-05-13):
mailR has been updated to allow different character encodings. Below is an example to send the message as UTF-8.
I would give up on using R for this. Working, cross-platform, stable solutions for doing this in Python exist, and you can call Python from R.
If I had to fit a mixed effects model in a Python program I'd call R to do it - if I want to do a systems task like send email in R I'll call Python to do it. Its worth learning if you don't know it yet.
Note that current versions of
sendmailR
support attachments out of the box by makingmsg
a list ofmime_type
objects, i.e. you'd nowHere's an example that is setup for a daily batch job like setting using sendmail() in R (available with the package sendmailR) with multiple attachments (one CSV, one PDF):
Setting up date information to reference in the file names:
Now create some of the needed information for sendmail() function at the end of this post:
Specify mail server here:
Define attachment 1 path and name:
Define attachment 1 object:
Define attachment 2 path and name:
Define attachment 2 object:
Now combine the body of the email with your attachments:
Send the email using sendmail() function: