Javamail (Version 1.2) Jaf (Version 1.1.1) : // File Name Sendemail - Java
Javamail (Version 1.2) Jaf (Version 1.1.1) : // File Name Sendemail - Java
Javamail (Version 1.2) Jaf (Version 1.1.1) : // File Name Sendemail - Java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendEmail
Sent message successfully....
If you want to send an e-mail to multiple recipients then following methods would
be used to specify multiple e-mail IDs:
type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and
BCC represents Black Carbon Copy. Example Message.RecipientType.TO
addresses: This is the array of email ID. You would need to use InternetAddress()
method while specifying email IDs
Send an HTML E-mail:
Here is an example to send an HTML email from your machine. Here it is assumed
that your localhostis connected to the internet and capable enough to send an
email.
This example is very similar to previous one, except here we are using
setContent() method to set content whose second argument is "text/html" to
specify that the HTML content is included in the message.
Using this example, you can send as big as HTML content you like.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendHTMLEmail
Sent message successfully....
Send Attachment in E-mail:
Here is an example to send an email with attachment from your machine. Here it
is assumed that yourlocalhost is connected to the internet and capable enough to
send an email.
// File Name SendFileEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendFileEmail
Sent message successfully....
User Authentication Part:
If it is required to provide user ID and Password to the e-mail server for
authentication purpose then you can set these properties as follows:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");