Javax.mail.internet.mimemessage
javax.mail.internet.MimeMessage
is a class in the JavaMail API that represents a MIME (Multipurpose Internet Mail Extensions) message. It is used to create and manipulate email messages that can be sent over the internet.
Here are some key features and methods of the MimeMessage
class:
Constructors:
MimeMessage(Session session)
: Creates a newMimeMessage
object with the specifiedSession
object.MimeMessage()
: Creates a newMimeMessage
object with a defaultSession
object.
Methods:
addHeader(String name, String value)
: Adds a header to the message with the specified name and value.addHeader(String name, String value, String charset)
: Adds a header to the message with the specified name, value, and character set.setContent(String text, String type)
: Sets the content of the message to the specified text and type (e.g., "text/plain" or "text/html").setContent(InputStream content, String type)
: Sets the content of the message to the specified input stream and type.setSubject(String subject)
: Sets the subject of the message.setFrom(InternetAddress from)
: Sets the sender of the message.addRecipient(Message.RecipientType type, InternetAddress address)
: Adds a recipient to the message.setSentDate(Date sentDate)
: Sets the date and time the message was sent.saveChanges()
: Saves any changes made to the message.
Properties:
getHeader(String name)
: Returns the value of the header with the specified name.getHeaders()
: Returns a list of all headers in the message.getContent()
: Returns the content of the message as aString
.getContentType()
: Returns the content type of the message.getSubject()
: Returns the subject of the message.getFrom()
: Returns the sender of the message.getRecipients(Message.RecipientType type)
: Returns a list of recipients of the message.
Example usage:
Here is an example of how to use the MimeMessage
class to create and send an email message:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// Create a session
Session session = Session.getDefaultInstance(new Properties(), null);
// Create a message
MimeMessage message = new MimeMessage(session);
// Set the sender and recipient
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
// Set the subject and content
message.setSubject("Test email");
message.setContent("Hello, this is a test email!", "text/plain");
// Send the message
Transport.send(message);
}
}
This example creates a MimeMessage
object, sets the sender, recipient, subject, and content, and then sends the message using the Transport.send()
method.