Last active
June 8, 2016 05:49
-
-
Save AravindaM/f16da73c1e8f0654e38b to your computer and use it in GitHub Desktop.
Sample Gmail Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.mail.*; | |
import javax.mail.internet.AddressException; | |
import javax.mail.internet.InternetAddress; | |
import javax.mail.internet.MimeMessage; | |
import java.util.Properties; | |
public class SampleMailClient { | |
private static String USER_NAME = "ara123@gmail.com"; // GMail user name (just the part before "@gmail.com") | |
private static String PASSWORD = "pass@1235"; // GMail password | |
private static String RECIPIENT = "ara1234@gmail.com"; | |
public static void main(String[] args) { | |
String from = USER_NAME; | |
String pass = PASSWORD; | |
String[] to = {RECIPIENT}; // list of recipient email addresses | |
String subject = "Java send mail example"; | |
String body = "Welcome to JavaMail!"; | |
sendFromGMail(from, pass, to, subject, body); | |
} | |
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { | |
Properties props = System.getProperties(); | |
String host = "smtp.gmail.com"; | |
props.put("mail.smtp.starttls.enable", "true"); | |
props.put("mail.smtp.host", host); | |
props.put("mail.smtp.user", from); | |
props.put("mail.smtp.password", pass); | |
props.put("mail.smtp.port", "587"); | |
props.put("mail.smtp.auth", "true"); | |
Session session = Session.getDefaultInstance(props); | |
MimeMessage message = new MimeMessage(session); | |
try { | |
message.setFrom(new InternetAddress(from)); | |
InternetAddress[] toAddress = new InternetAddress[to.length]; | |
// To get the array of addresses | |
for (int i = 0; i < to.length; i++) { | |
toAddress[i] = new InternetAddress(to[i]); | |
} | |
for (int i = 0; i < toAddress.length; i++) { | |
message.addRecipient(Message.RecipientType.TO, toAddress[i]); | |
} | |
message.setSubject(subject); | |
message.setText(body); | |
Transport transport = session.getTransport("smtp"); | |
transport.connect(host, from, pass); | |
transport.sendMessage(message, message.getAllRecipients()); | |
transport.close(); | |
} catch (AddressException ae) { | |
ae.printStackTrace(); | |
} catch (MessagingException me) { | |
me.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment