How to create write mail with the attachement file
Here are the steps to create a mail with an attachment file using various programming languages:
Python using smtplib and email libraries
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
def send_email(subject, message, from_addr, to_addr, smtp_server, smtp_port, smtp_user, smtp_pass, attachment_file):
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(message, 'plain'))
attachment = open(attachment_file, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename= {attachment_file}')
msg.attach(part)
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_user, smtp_pass)
text = msg.as_string()
server.sendmail(from_addr, to_addr, text)
server.quit()
# Example usage
subject = "Test Email with Attachment"
message = "This is a test email with an attachment."
from_addr = "[email protected]"
to_addr = "[email protected]"
smtp_server = "smtp.gmail.com"
smtp_port = 587
smtp_user = "[email protected]"
smtp_pass = "your_password"
attachment_file = "path/to/your/file.txt"
send_email(subject, message, from_addr, to_addr, smtp_server, smtp_port, smtp_user, smtp_pass, attachment_file)
Java using JavaMail API
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
public class SendEmailWithAttachment {
public static void main(String[] args) {
String subject = "Test Email with Attachment";
String message = "This is a test email with an attachment.";
String from = "[email protected]";
String to = "[email protected]";
String host = "smtp.gmail.com";
int port = 587;
String user = "[email protected]";
String pass = "your_password";
String attachmentFile = "path/to/your/file.txt";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", String.valueOf(port));
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
try {
Message messageObj = new MimeMessage(session);
messageObj.setFrom(new InternetAddress(from));
messageObj.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
messageObj.setSubject(subject);
messageObj.setText(message);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File(attachmentFile));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(attachmentPart);
messageObj.setContent(multipart);
Transport.send(messageObj);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
C# using System.Net.Mail
using System;
using System.Net.Mail;
using System.Net.Mime;
public class SendEmailWithAttachment {
public static void Main(string[] args) {
string subject = "Test Email with Attachment";
string message = "This is a test email with an attachment.";
string from = "[email protected]";
string to = "[email protected]";
string host = "smtp.gmail.com";
int port = 587;
string user = "[email protected]";
string pass = "your_password";
string attachmentFile = "path/to/your/file.txt";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Subject = subject;
mail.Body = message;
Attachment attachment = new Attachment(attachmentFile);
mail.Attachments.Add(attachment);
SmtpClient client = new SmtpClient();
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(user, pass);
client.Send(mail);
Console.WriteLine("Email sent successfully!");
}
}
Node.js using nodemailer
const nodemailer = require('nodemailer');
async function sendEmail() {
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // or 'STARTTLS'
auth: {
user: '[email protected]',
pass: 'your_password'
}
});
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Test Email with Attachment',
text: 'This is a test email with an attachment.',
attachments: [
{ path: 'path/to/your/file.txt' }
]
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Email sent: ' + info.response);
});
}
sendEmail();
Make sure to replace the placeholders ([email protected]
, your_password
, [email protected]
, path/to/your/file.txt
) with your actual email credentials and file path.