Java - Mail For Developers

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

void sendMail2() {

String to = "to@gmail.com";

// Sender's email ID needs to be mentioned


String from = "from@gmail.com";
// final String username = "Notification";//change accordingly
final String password = "parol";//change accordingly

// Assuming you are sending email through relay.jangosmtp.net


String host = "smtp.gmail.com";

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", "587");
props.put("mail.user", from);
props.put("mail.password", password);

// Get the Session object.


Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});

try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);

// Set From: header field of the header.


message.setFrom(new InternetAddress(from));

// Set To: header field of the header.


String recipient = "to1@gmail.com ,to2@gmail.com";
String[] recipientList = recipient.split(",");
InternetAddress[] cc = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipientin : recipientList) {
cc[counter] = new InternetAddress(recipientin.trim());
counter++;
}
message.setRecipients(Message.RecipientType.TO,
cc);

// Set Subject: header field


message.setSubject("Testing Subject");

// Send the actual HTML message, as big as you like


message.setContent(
"<table border=\"1\" style=\"border-collapse: collapse;\" >\n"
+ " <tr>\n"
+ " <th>Company</th>\n"
+ " <th>Contact</th>\n"
+ " <th>Country</th>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Alfreds Futterkiste</td>\n"
+ " <td>Maria Anders</td>\n"
+ " <td>Germany</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Centro comercial Moctezuma</td>\n"
+ " <td>Francisco Chang</td>\n"
+ " <td>Mexico</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Ernst Handel</td>\n"
+ " <td>Roland Mendel</td>\n"
+ " <td>Austria</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Island Trading</td>\n"
+ " <td>Helen Bennett</td>\n"
+ " <td>UK</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Laughing Bacchus Winecellars</td>\n"
+ " <td>Yoshi Tannamuri</td>\n"
+ " <td>Canada</td>\n"
+ " </tr>\n"
+ " <tr>\n"
+ " <td>Magazzini Alimentari Riuniti</td>\n"
+ " <td>Giovanni Rovelli</td>\n"
+ " <td>Italy</td>\n"
+ " </tr>\n"
+ "</table>", "text/html");

// Send message
Transport.send(message);

System.out.println("Sent message successfully....");

} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

You might also like