18 Ağustos 2009 Salı

JAVA ile mail gonderme 2

String to = ""; // to address
String from = ""; // from address
String subject = ""; // the subject line
String message = null; // the body of the message
String mailhost = ""; // SMTP server
String user = ""; // user ID
String password = ""; // password
// password
boolean auth = true;
boolean ssl = false;
Properties props = System.getProperties();

if (mailhost != null) {
props.put("mail.smtp.host", mailhost);
}
if (auth) {
props.put("mail.smtp.auth", "true");
}
// Get a Session object
javax.mail.Session session = javax.mail.Session.getInstance(props, null);

// Construct the message
javax.mail.Message msg = new MimeMessage(session);

try {
// Set message details
msg.setFrom(new InternetAddress(from));
msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);

// Send the thing off
SMTPTransport t = (SMTPTransport)session.getTransport(ssl ? "smtps" : "smtp");
try {
if (auth) {
t.connect(mailhost, user, password);
} else {
t.connect();
}
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}
log("Mail was sent successfully.");
} catch (Exception e) {
if (e instanceof SendFailedException) {
MessagingException sfe = (MessagingException)e;
if (sfe instanceof SMTPSendFailedException) {
SMTPSendFailedException ssfe = (SMTPSendFailedException)sfe;
log("Smtp_Send_Failed:");
}
Exception ne;
while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
sfe = (MessagingException)ne;
if (sfe instanceof SMTPAddressFailedException) {
SMTPAddressFailedException ssfe = (SMTPAddressFailedException)sfe;
log("Address failed:");
log(ssfe.toString());
log(" Address: " + ssfe.getAddress());
log(" Command: " + ssfe.getCommand());
log(" Return Code: " + ssfe.getReturnCode());
log(" Response: " + ssfe.getMessage());
} else if (sfe instanceof SMTPAddressSucceededException) {
log("Address succeeded:");
SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException)sfe;
}
}
} else {
log("Got Exception : " + e);
}
}

Hiç yorum yok: