Java code for authenticating into SMTP server with auth and TLS turned on ..
After a long search I Came internal SS this sample Java code for sending
Email into an SMTP server which required authentication and secure (TLS)
Connection. Hence I thought, I will re-publish it. I found this piece
Of code from Java developer forums... I cocould not trace back
Link... thanks to good soul who published it. I thought of re-publishing
It due its rarity.
I have used Java mail 1.4.
------------------------------- Java code ---------------------------
Import javax. Mail .*;
Import javax. Mail. Internet .*;
Import java. util .*;
Public class main
{
String d_email = "ADDRESS@gmail.com ",
D_password = "password ",
D_host = "smtp.gmail.com ",
D_port = "465 ",
M_to = "email address ",
M_subject = "testing ",
M_text = "Hey, this is the testing email .";
Public main ()
{
Properties props = new properties ();
Props. Put ("mail. SMTP. User", d_email );
Props. Put ("mail. SMTP. Host", d_host );
Props. Put ("mail. SMTP. Port", d_port );
Props. Put ("mail. SMTP. starttls. Enable", "true ");
Props. Put ("mail. SMTP. Auth", "true ");
// Props. Put ("mail. SMTP. debug", "true ");
Props. Put ("mail. SMTP. socketfactory. Port", d_port );
Props. Put ("mail. SMTP. socketfactory. Class", "javax.net. SSL. sslsocketfactory ");
Props. Put ("mail. SMTP. socketfactory. Fallback", "false ");
Securitymanager SECURITY = system. getsecuritymanager ();
Try
{
Authenticator auth = new smtpauthenticator ();
Session session = session. getinstance (props, auth );
// Session. setdebug (true );
Mimemessage MSG = new mimemessage (session );
MSG. settext (m_text );
MSG. setsubject (m_subject );
MSG. setfrom (New internetaddress (d_email ));
MSG. addrecipient (message. recipienttype. To, new internetaddress (m_to ));
Transport. Send (MSG );
}
Catch (exception MEX)
{
Mex. printstacktrace ();
}
}
Public static void main (string [] ARGs)
{
Main blah = new main ();
}
Private class smtpauthenticator extends javax. Mail. authenticator
{
Public passwordauthentication getpasswordauthentication ()
{
Return new passwordauthentication (d_email, d_password );
}
}
}