SMTP authenticated or not

4 views
Skip to first unread message

Isaac4given

unread,
Aug 13, 2007, 4:04:00 PM8/13/07
to WITL (Walk In The Light)
Here is the code to send authenticated email:

public static void main(String args[]) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", JOptionPane
.showInputDialog("Your SMTP server name?"));
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Message msg = new MimeMessage(Session.getDefaultInstance(props,
auth));
InternetAddress addressFrom = new InternetAddress(
"i...@users.sourceforge.net");
msg.setFrom(addressFrom);
msg.setRecipients(Message.RecipientType.TO,
new InternetAddress[] { new InternetAddress(
"i...@users.sourceforge.net") });
msg.setContent("test", "text/plain");
Transport.send(msg);
System.exit(0);
}

private static class SMTPAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("login", JOptionPane
.showInputDialog("Password?"));
}
}

And not authenticated:

Properties props = new Properties();
props.put("mail.smtp.host", JOptionPane
.showInputDialog("Your SMTP server name?"));
Message msg = new MimeMessage(Session.getDefaultInstance(props));
InternetAddress addressFrom = new InternetAddress(
"i...@users.sourceforge.net");
msg.setFrom(addressFrom);
msg.setRecipients(Message.RecipientType.TO,
new InternetAddress[] { new InternetAddress(
"i...@users.sourceforge.net") });
msg.setContent("test", "text/plain");
Transport.send(msg);
System.exit(0);

As you can see, sending mail without SMTP authentication is much
simpler. However, some SMTP servers require authentication and some
don't. The trick is to figure out whether your SMTP requires
authentication or not, and then proceed accordingly.

Isaac4given

unread,
Aug 15, 2007, 6:51:41 PM8/15/07
to WITL (Walk In The Light)
Here is code to ask authentication, and support SMTP with or without
it:

if (JOptionPane.showConfirmDialog(null,
"Does your SMTP server require authentication?",
"Authentication?", JOptionPane.YES_NO_OPTION) ==
JOptionPane.YES_OPTION) {


props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();

msg = new MimeMessage(Session.getDefaultInstance(props, auth));

} else {
msg = new MimeMessage(Session.getDefaultInstance(props));
}

The full program:

http://groups.google.com/group/witl/web/SendMail2.java

Reply all
Reply to author
Forward
0 new messages