[![X-51 © 2015 MARVEL][logo]](http://oshliaer.github.io/marvel/)

# Create a Gmail draft with attachments via Google Apps Script #gas #gmail
- Gmail API [Users.drafts](https://developers.google.com/gmail/api/v1/reference/users/drafts)
- [Multipurpose Internet Mail Extensions PART#1](http://www.rfc-editor.org/rfc/rfc1521.txt)
- [Multipurpose Internet Mail Extensions PART#2](http://tools.ietf.org/html/rfc2046)
- [Media Types](http://www.iana.org/assignments/media-types/media-types.xhtml)
- [The contentType is now "message/rfc822" instead of "application/json"](http://stackoverflow.com/a/24957873) thanks [Tholle from `SO`](http://stackoverflow.com/users/3617886/tholle)

# How to use
## Intro
Copy [Message.gs](https://gist.github.com/oshliaer/7e96514c3cb3075dde02#file-message-gs) to your project. You have to [enable advanced services](https://developers.google.com/apps-script/guides/services/advanced?hl=en#enabling_advanced_services) for Gmail API.

Be sure your project has next files:
 * [quoted-printable.js](https://github.com/mathiasbynens/quoted-printable.git). Rename to `gs`.
 * [utf8.js](https://github.com/mathiasbynens/utf8.js.git). Rename to `gs`.

### Additional
Clone

```bash
git clone https://gist.github.com/7e96514c3cb3075dde02.git
```

For biulds you have to have git & node & npm. Then you can

```bash
git clone https://gist.github.com/7e96514c3cb3075dde02.git && npm install
```

It's strange but it can be.

For the tests you need to connect the [TestApp Library](https://github.com/Spencer-Easton/Apps-Script-TestApp-Library)

## Create a draft

```javascript
var msg = new Message();
msg.to = 'test@test.ru';
msg.body = '<h1>TEST</h1>';
msg.subject = 'TEST';
var file = DriveApp.createFile('~myfile.txt', 'content' + new Date(), 'text/plain');
msg.attachments = [file];
msg.createDraft();
```

## Define several attachments

```javascript
msg.attachments = [File, File];
```

`File` is a [file in Google Drive](https://developers.google.com/apps-script/reference/drive/file). Files can be accessed or created from DriveApp.

## Create with existing file

```javascript
var file = DriveApp.getFileById(id);
msg.attachments = [file];
```

## Create with existing files from a folder

```javascript
var filesi = DriveApp.getFolderById(id).getFilesByType('text/plain');
var files = [];
while(filesi.hasNext()){
    files.push(filesi.next());
}
msg.attachments = files;
```

## Create as a thread's child

```javascript
...
var thread = Gmail.Users.Threads.list('me').threads[0].id;
msg.threadId = thread;
var resp = msg.createDraft();
```

[logo]: http://i.annihil.us/u/prod/marvel/i/mg/f/d0/4c003727804b4/landscape_small.jpg