Smtp üzerinden authenticate mail gönderimi

Java ile mail gönderirken authenticate olmak yani mail kullanıcısı ile oturum açmak istiyorsak aşağıdaki örnek kodu kullanabiliriz. Bu arada java mail için gerekli olan mail.jar ve activation.jar kütüphanelerinizin classpath e ekli olması gerekiyor.

    import java.util.Properties;
     
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMessage.RecipientType;
     
    public class EmailTest{
     public static void main(String[] args) throws MessagingException {
      EmailTest m = new EmailTest();
      Message message = new MimeMessage(m.getSession());
     
      message.addRecipient(RecipientType.TO, new InternetAddress("melih.sakarya@gmail.com"));
      message.addFrom(new InternetAddress[] { new InternetAddress("info@xyz.com") });
     
      message.setSubject("Deneme amacli mesaj");
      message.setContent("Mesaj icerik", "text/plain");
     
      Transport.send(message);
     }
     
     private Session getSession() {
      Authenticator authenticator = new Authenticator();
     
      Properties properties = new Properties();
      properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
      properties.setProperty("mail.smtp.auth", "true");
     
      properties.setProperty("mail.smtp.host", "mail.xyz.com");
      properties.setProperty("mail.smtp.port", "25");
     
      return Session.getInstance(properties, authenticator);
     }
     
     private class Authenticator extends javax.mail.Authenticator {
      private PasswordAuthentication authentication;
     
      public Authenticator() {
       String username = "info@xyz.com";
       String password = "123456";
       authentication = new PasswordAuthentication(username, password);
      }
     
      protected PasswordAuthentication getPasswordAuthentication() {
       return authentication;
      }
     }
    }
No comments yet.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>