How to pass header into the mail
To pass a header into an email, you can use the headers
parameter when sending the email using a programming language or a library. Here are some examples:
Python (using smtplib and email libraries)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'Test Email'
# Add a custom header
msg['X-Custom-Header'] = 'Hello, World!'
body = 'This is the email body.'
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.example.com')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
Java (using JavaMail API)
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
msg.setSubject("Test Email");
// Add a custom header
msg.addHeader("X-Custom-Header", "Hello, World!");
String body = "This is the email body.";
msg.setText(body);
Transport.send(msg);
Node.js (using nodemailer)
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
host: 'smtp.example.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',
text: 'This is the email body.',
headers: {
'X-Custom-Header': 'Hello, World!'
}
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Email sent: ' + info.response);
});
In each example, the headers
parameter is used to add a custom header to the email. The key is the name of the header (e.g. X-Custom-Header
) and the value is the value of the header (e.g. Hello, World!
).