How to pass message object in javax mail
In JavaMail, you can pass a Message
object to a Transport
object to send the message. Here's an example:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// Create a session
Session session = Session.getDefaultInstance(new Properties(), null);
// Create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
msg.setSubject("Hello");
msg.setText("Hello, world!");
// Create a transport
Transport transport = session.getTransport();
// Pass the message to the transport
transport.sendMessage(msg, msg.getAllRecipients());
In this example, we create a MimeMessage
object and set its properties (from, to, subject, and text). We then create a Transport
object using the Session
object, and pass the Message
object to the sendMessage()
method along with the list of recipients.
Note that the sendMessage()
method returns a void
value, so you don't need to worry about getting a response back from the transport.
Alternatively, you can use the Message
object to send a message using a SMTP
transport:
// Create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
msg.setSubject("Hello");
msg.setText("Hello, world!");
// Create a SMTP transport
Transport transport = session.getTransport("smtp");
transport.connect("smtp.example.com", "username", "password");
// Pass the message to the transport
transport.sendMessage(msg, msg.getAllRecipients());
// Close the transport
transport.close();
In this example, we create a MimeMessage
object and set its properties as before. We then create a Transport
object using the Session
object and specify the transport protocol as "smtp". We connect to the SMTP server using the connect()
method, and then pass the Message
object to the sendMessage()
method along with the list of recipients. Finally, we close the transport using the close()
method.