Last active
May 26, 2017 13:58
-
-
Save pethaniakshay/c14afcfc90ee2447d4a1e523ac878d3b to your computer and use it in GitHub Desktop.
Java Program to send Email through SMTP server of Gmail. API used: Java Mail API by Oracle.
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 java.util.Properties; | |
import javax.mail.*; | |
import javax.mail.internet.*; | |
class Mailer{ | |
public static void send(String from,String password,String to,String sub,String msg){ | |
//Get properties object | |
Properties props = new Properties(); | |
props.put("mail.smtp.host", "smtp.gmail.com"); | |
props.put("mail.smtp.socketFactory.port", "465"); | |
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); | |
props.put("mail.smtp.auth", "true"); | |
props.put("mail.smtp.port", "465"); | |
//get Session | |
Session session = Session.getDefaultInstance(props, | |
new javax.mail.Authenticator() { | |
@Override | |
protected PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(from,password); | |
} | |
} | |
); | |
//compose message | |
try { | |
MimeMessage message = new MimeMessage(session); | |
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); | |
message.setSubject(sub); | |
message.setText(msg); | |
//send message | |
Transport.send(message); | |
System.out.println("message sent successfully"); | |
} catch (MessagingException e) {throw new RuntimeException(e);} | |
} | |
} | |
public class SendMail{ | |
public static void main(String[] args) { | |
Mailer.send("yourgmail mail [email protected]","your gmail Password","[email protected]","This is mail Heading","This is mail body"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code Puran