Learn how to send attachments in email.
Sending emails with attachments is easy with SMTP. This guide shows how to send attachments with SMTP using NodeMailer and Powershell.
Attachments are sent with multipart MIME in SMTP by dividing the message body into multiple parts, each with its own MIME type and headers, and including the attachment as one of these parts.
To send an attachment with SMTP, the message is typically composed using the multipart/mixed MIME type. This MIME type allows for multiple parts, each with its own MIME type, to be included in the message body. The message header includes a boundary parameter that defines a unique string to separate the parts of the message.
The first part of the message is typically a text/plain or text/html part containing the body of the message. This part is followed by one or more parts containing the attachments. Each attachment part has a content-type set to the appropriate MIME type for the attachment file, and a content-disposition header that specifies the filename and the disposition type (attachment or inline).
When the email message is received by the recipient's email client, the multipart/mixed content is parsed, and the body and attachments are displayed accordingly. The email client typically displays the body text in the message body and displays the attachments as separate files or inline content, depending on the content-disposition header.
In summary, sending attachments with SMTP using multipart MIME involves creating a multipart/mixed message with a boundary parameter, adding a text/plain or text/html part for the message body, and adding one or more parts for the attachments, each with its own content-type and content-disposition headers. When the email message is received, the parts are parsed and displayed as appropriate.
NodeMailer Javascript SMTP attachments example
You can send emails with attachments using NodeMailer and Javascript. The following example shows how to send an email with an attachment using NodeMailer and Javascript.
describe("testing smtp", function () {
it("can create an mailbox and get email preview urls", async function () {
const apiKey = process.env.API_KEY;
if (!apiKey) {
throw new Error("Please set API_KEY environment variable")
}
const mailslurp = new MailSlurp({apiKey, fetchApi})
const access = await mailslurp.getImapSmtpAccessDetails();
expect(access).toBeTruthy();
const inbox1 = await mailslurp.createInboxWithOptions({inboxType: 'SMTP_INBOX'})
const inbox2 = await mailslurp.createInboxWithOptions({inboxType: 'SMTP_INBOX'})
const transporter = nodemailer.createTransport({
host: access.smtpServerHost,
port: access.smtpServerPort,
secure: false,
auth: {
user: access.smtpUsername,
pass: access.smtpPassword
},
});
const sent = await transporter.sendMail({
from: inbox1.emailAddress,
to: inbox2.emailAddress,
subject: "From inbox 1 to inbox 2",
text: "Hi there",
attachments: [
{
filename: "example.txt",
content: new Buffer('hello world!','utf-8')
}
],
});
expect(sent).toBeTruthy()
const email = await mailslurp.waitForLatestEmail(inbox2.id, 30_000, true);
expect(email.subject).toEqual("From inbox 1 to inbox 2")
expect(email.attachments.length).toEqual(1)
const accessUrls = await mailslurp.emailController.getEmailPreviewURLs({emailId: email.id})
// access these urls in browser to view email content
expect(accessUrls.plainHtmlBodyUrl).toContain("https://api.mailslurp.com")
expect(accessUrls.rawSmtpMessageUrl).toContain("https://api.mailslurp.com")
});
});
How to send attachments in email with Windows Powershell
# set the sender and recipient email addresses
$sender = "your_email_address"
$recipient = "recipient_email_address"
# set the subject and body of the email
$subject = "Test Email with Attachment"
$body = "This is a test email with attachment."
# set the attachment file name and path
$filename = "example.txt"
$filepath = "C:\path\to\example.txt"
# create a boundary string
$boundary = [System.Guid]::NewGuid().ToString()
# create a MIME message object
$message = New-Object System.Net.Mail.MailMessage $sender, $recipient
$message.Subject = $subject
$message.Body = $body
# create an attachment object and add it to the message object
$attachment = New-Object System.Net.Mail.Attachment $filepath
$attachment.ContentDisposition.FileName = $filename
$message.Attachments.Add($attachment)
# create a MIME content object
$content = New-Object System.Net.Mime.MultipartRelated
$content.Boundary = $boundary
$body = New-Object System.Net.Mail.AlternateView("This is a test email with attachment.")
$content.Add($body)
$content.Add($attachment)
# set the message content type and add the content to the message
$message.IsBodyHtml = $true
$message.Body = $body
$message.AlternateViews.Add($content)
# create an SMTP client object and send the message
$smtp = New-Object System.Net.Mail.SmtpClient "mailslurp.mx", 587
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential $sender, "your_email_password"
$smtp.Send($message)
# dispose of the attachment object and message object
$attachment.Dispose()
$message.Dispose()
Sending attachments via SMTP with bash script
#!/bin/bash
# set the sender and recipient email addresses
sender="your_email_address"
recipient="recipient_email_address"
# set the subject and body of the email
subject="Test Email with Attachment"
body="This is a test email with attachment."
# set the attachment file name and path
filename="example.txt"
filepath="/path/to/example.txt"
# create a boundary string
boundary=$(uuidgen)
# build the email message body
{
echo "From: ${sender}"
echo "To: ${recipient}"
echo "Subject: ${subject}"
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/mixed; boundary=${boundary}"
echo ""
echo "--${boundary}"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Disposition: inline"
echo ""
echo "${body}"
echo ""
echo "--${boundary}"
echo "Content-Type: application/octet-stream"
echo "Content-Disposition: attachment; filename=${filename}"
echo ""
cat "${filepath}"
echo ""
echo "--${boundary}--"
} | /usr/sbin/sendmail -t
Sending attachments in email Python
Here's a tutorial on how to send attachments in SMTP email using Python's built-in smtplib and email modules:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# create message object instance
msg = MIMEMultipart()
# set the sender and recipient email addresses
sender = 'your_email_address'
recipient = 'recipient_email_address'
# set the subject and body of the email
msg['Subject'] = 'Test Email with Attachment'
msg['From'] = sender
msg['To'] = recipient
body = 'This is a test email with attachment.'
# attach the body of the email to the message object
msg.attach(MIMEText(body, 'plain'))
# open the file in bynary
filename = "example.txt"
attachment = open("example.txt", "rb")
# create a MIMEBase object and set its attributes
file = MIMEBase('application', 'octet-stream')
file.set_payload((attachment).read())
encoders.encode_base64(file)
file.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the MIMEBase object to the message object
msg.attach(file)
# create a SMTP session
server = smtplib.SMTP('mailslurp.mx', 587)
# start TLS for security
server.starttls()
# authenticate with the email account
server.login(sender, 'your_email_password')
# send the email
server.sendmail(sender, recipient, msg.as_string())
# terminate the SMTP session
server.quit()
In this code example, we first import the necessary modules: smtplib, MIMEText, MIMEMultipart, MIMEBase, and encoders. We then create a MIMEMultipart message object and set its attributes, including the sender and recipient email addresses, the subject and body of the email, and the attachment.
Next, we open the file to be attached in binary mode, create a MIMEBase object, and set its attributes, including the file type and name. We then encode the attachment with base64 and attach it to the message object.
We then create a SMTP session with the email server, start TLS for security, authenticate with the email account, and send the email using the sendmail() method. Finally, we terminate the SMTP session.
Note that in this example, we're using a Gmail SMTP server. If you're using a different email provider, you'll need to adjust the SMTP server settings accordingly.