Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/muratgozel/mimetext
RFC-2822, RFC-2045 and RFC-2049 compliant raw email message generator.
https://github.com/muratgozel/mimetext
amazon-ses attachment email email-attachments email-message-header email-parsing mime-message mimetext nodejs-library rfc-2045 rfc-2049 rfc-2822
Last synced: 2 days ago
JSON representation
RFC-2822, RFC-2045 and RFC-2049 compliant raw email message generator.
- Host: GitHub
- URL: https://github.com/muratgozel/mimetext
- Owner: muratgozel
- License: mit
- Created: 2019-06-26T20:58:22.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2024-05-19T22:39:32.000Z (7 months ago)
- Last Synced: 2024-12-14T09:06:55.432Z (9 days ago)
- Topics: amazon-ses, attachment, email, email-attachments, email-message-header, email-parsing, mime-message, mimetext, nodejs-library, rfc-2045, rfc-2049, rfc-2822
- Language: JavaScript
- Homepage: https://muratgozel.github.io/MIMEText/
- Size: 2.98 MB
- Stars: 84
- Watchers: 2
- Forks: 35
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# MIMEText
[RFC-2822](https://www.rfc-editor.org/rfc/rfc2822), [RFC-2045](https://www.rfc-editor.org/rfc/rfc2045) and [RFC-2049](https://www.rfc-editor.org/rfc/rfc2049) compliant raw email message generator. Refer to [https://muratgozel.github.io/MIMEText/](https://muratgozel.github.io/MIMEText/) for full api docs.It has full typings. Optimized to run on node, browser and google apps script environments. Compatible with commonjs and esm.
## Install
```sh
npm i mimetext
```There is special version for Google Apps Script environment which can be found under dist folder: `./dist/gas.js` or `./dist/gas.cjs`
## Use
Import the appropriate version for your environment. Use `mimetext/browser` for browser and `mimetext` for node environments.
```js
// es
import {createMimeMessage} from 'mimetext'
// or const {createMimeMessage} = require('mimetext') for commonjs// create a simple plain text email
const msg = createMimeMessage()
msg.setSender({name: 'Lorem Ipsum', addr: '[email protected]'})
msg.setRecipient('[email protected]')
msg.setSubject('🚀 Issue 49!')
msg.addMessage({
contentType: 'text/plain',
data: `Hi,
I'm a simple text.`
})
const raw = msg.asRaw()
/*
Date: Sun, 24 Oct 2021 04:50:32 +0000
From: "Lorem Ipsum"
To:
Message-ID:
Subject: =?utf-8?B?8J+agCBJc3N1ZSA0OSE=?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8Hi,
I'm a simple text.
*/
```### Different Ways Of Adding Recipients
There are more than one method and format to add recipients:
```js
// adds recipient to To field by default
msg.setRecipient('Firstname Lastname ')
// you can specify To, Cc, Bcc
msg.setRecipient('Firstname Lastname ', {type: 'Cc'})
// as object, only addr is required
msg.setRecipient({addr: '[email protected]', name: 'Firstname Lastname', type: 'Bcc'})
// shortcut methods
msg.setTo('[email protected]')
msg.setCc('[email protected]')
msg.setBcc('[email protected]')
// multiple recipient at once
msg.setRecipients('[email protected]', 'Firstname Lastname ', {addr: '[email protected]'})// similarly you can set the sender
msg.setSender('First Last ')
msg.setSender({name: 'First Last', addr: '[email protected]'})
```### HTML Message With Plain Text Fallback And Attachments
You can set html and plain text messages both and recipients mail client will render however they think appropriate.The example below demonstrates more sophisticated email content including inline attachments and regular attachments.
```js
const msg = createMimeMessage()
msg.setSender('[email protected]')
msg.setRecipients('[email protected]')
msg.setSubject('Testing MimeText 🐬 (Plain Text + HTML With Mixed Attachments)')
msg.addMessage({
contentType: 'text/plain',
data: 'Hello there,' + EOL + EOL +
'This is a test email sent by MimeText test suite.'
})
// specify inline attachment's content id inside img src tag.
msg.addMessage({
contentType: 'text/html',
data: 'Hello there,
' +
'This is a test email sent by MimeText test suite.
' +
'The term MimeText above supposed to be bold. Are you able to see it?
' +
'Below, there should be a small image that contains little black dots:
' +
'
' +
'Best regards.'
})
msg.addAttachment({
filename: 'sample.jpg',
contentType: 'image/jpg',
data: '...base64 encoded data...'
})
msg.addAttachment({
filename: 'sample.txt',
contentType: 'text/plain',
data: '...base64 encoded data...'
})
// this is inline attachment!
msg.addAttachment({
inline: true,
filename: 'dots.jpg',
contentType: 'image/jpg',
data: '...base64 encoded data...',
headers: {'Content-ID': 'dots123456'}
})
const raw = msg.asRaw()
/*
Date: Sun, 26 Mar 2023 13:27:15 +0000
From:
To:
Message-ID:
Subject: =?utf-8?B?VGVzdGluZyBNaW1lVGV4dCDwn5CsIChQbGFpbiBUZXh0ICsgSFRNTCBXaXRoIE1peGVkIEF0dGFjaG1lbnRzKQ==?=
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=giev1zqo579--giev1zqo579
Content-Type: multipart/related; boundary=hl6rtnn5jq--hl6rtnn5jq
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bitHello there,
This is a test email sent by MimeText test suite.
The term MimeText above supposed to be bold. Are you able to see it?
Below, there should be a small image that contains little black dots:
Best regards.--hl6rtnn5jq
Content-ID:
Content-Type: image/jpg; name="dots.jpg"
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="dots.jpg"/9j/4AAQSkZJRgABAgEASABIAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQ...........BPwAp/9k=
--hl6rtnn5jq--
--giev1zqo579
Content-Type: image/jpg; name="sample.jpg"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sample.jpg"/9j/4AAQSkZJRgABAg...........befPb4N8Hn4A/9k=
--giev1zqo579
Content-Type: text/plain; name="sample.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sample.txt"SGVsbG8gdGhlcmUu
--giev1zqo579--
*/
```### Encoding The Output
If you ever need to get base64-websafe encoded version of the raw data, you can use `asEncoded()` method.
```js
// it first gets the raw version and then encodes it.
msg.asEncoded()
```## Use Cases
MIMEText is useful for email sending platforms and end-user apps whose email clients require raw email messages.Below you can find some examples for **Amazon SES** or **Google Gmail**.
### Amazon SES with AWS-SDK
ses client v1:
```js
// install with npm i @aws-sdk/client-ses// init aws sdk
const { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses')
const ses = new SESClient({ region: 'YOUR_REGION' })
const { Buffer } = require('node:buffer')// init mimetext
const { createMimeMessage } = require('mimetext')
const message = createMimeMessage()// create email message
message.setSender('[email protected]')
message.setTo('[email protected]')
message.setSubject('Weekly Newsletter 49 Ready 🚀')
message.addAttachment({
filename: 'bill.pdf',
contentType: 'application/pdf',
data: '...base64 encoded data...'
})
message.addMessage({
contentType: 'text/html',
data: 'Hello John.'
})// send email with aws sdk
const params = {
Destinations: message.getRecipients({type: 'to'}).map(mailbox => mailbox.addr),
RawMessage: {
Data: Buffer.from(message.asRaw(), 'utf8') // the raw message data needs to be sent as uint8array
},
Source: message.getSender().addr
}
const result = await ses.send(new SendRawEmailCommand(params))
// result.MessageId
```
ses client v2:
```js
// install with npm i @aws-sdk/client-sesv2// init aws sdk
const { SESv2Client, SendEmailCommand } = require('@aws-sdk/client-ses')
const ses = new SESv2Client({ region: 'YOUR_REGION' })
const { Buffer } = require('node:buffer')// init mimetext
const { createMimeMessage } = require('mimetext')
const message = createMimeMessage()// create email message
message.setSender('[email protected]')
message.setTo('[email protected]')
message.setSubject('Weekly Newsletter 49 Ready 🚀')
message.addAttachment({
filename: 'bill.pdf',
contentType: 'application/pdf',
data: '...base64 encoded data...'
})
message.addMessage({
contentType: 'text/html',
data: 'Hello John.'
})const params = {
FromEmailAddress: message.getSender().addr,
Destination: {
ToAddresses: message.getRecipients().map((box) => box.addr)
},
Content: {
Raw: {
Data: Buffer.from(message.asRaw(), 'utf8')
}
}
}
const result = await ses.send(new SendEmailCommand(params))
// result.MessageId
```### Google Gmail with googleapis-sdk
```js
// init google api sdk
const {google} = require('googleapis')// create email message
const {createMimeMessage} = require('mimetext')
const message = createMimeMessage()
message.setSender('[email protected]')
message.setTo('[email protected]')
message.setSubject('Weekly Newsletter 49 Ready 🚀')
message.addAttachment({
filename: 'bill.pdf',
contentType: 'application/pdf',
data: '...base64 encoded data...'
})
message.addMessage({
contentType: 'text/html',
data: 'Hello John.'
})// send email
google.auth
.getClient({scopes: ['https://www.googleapis.com/auth/gmail.send']})
.then(function(client) {
client.subject = '[email protected]'const gmail = google.gmail({ version: 'v1', auth: client })
gmail.users.messages
.send({
userId: 'me',
requestBody: {
raw: message.asEncoded()
}
})
.then(function(result) {
// result.id
})
.catch(function(err) {})
})
```## Error Handling
Most of the methods raises `MIMETextError` in case of invalid input. You can catch them and handle them accordingly.
```js
try {
message.setTo({prop: 'invalid'})
} catch (e) {
e instanceof MIMETextError === true
}
```## Contributing
If you're interested in contributing, read the [CONTRIBUTING.md](https://github.com/muratgozel/muratgozel/blob/main/CONTRIBUTING.md) first, please.---
Version management of this repository done by [releaser](https://github.com/muratgozel/node-releaser) 🚀
---
Thanks for watching 🐬
[![Support me on Patreon](https://cdn.muratgozel.com.tr/support-me-on-patreon.v1.png)](https://patreon.com/muratgozel?utm_medium=organic&utm_source=github_repo&utm_campaign=github&utm_content=join_link)