• Web sitemizin içeriğine ve tüm hizmetlerimize erişim sağlamak için Web sitemize kayıt olmalı ya da giriş yapmalısınız. Web sitemize üye olmak tamamen ücretsizdir.
  • Sohbetokey.com ile canlı okey oynamaya ne dersin? Hem sohbet et, hem mobil okey oyna!
  • Soru mu? Sorun mu? ''Bir Sorum Var?'' sistemimiz aktiftir. Paylaşın beraber çözüm üretelim.

Java ile Mail Gönderme – JavaMail API

Üyelik Tarihi
7 Ocak 2015
Konular
4,091
Mesajlar
4,274
MFC Puanı
40
Java uygulamaları içerisinden mail gönderme, JavaMail API sayesinde platform bağımsız ve protokol bağımsız olarak gerçekleştirilebiliyor.

Bu yazı da, Java ile mail göndermek için geliştirdiğim basit bir uygulamayı paylaşmak istiyorum. Uygulama, birden fazla mail adresine mail yollayabildiği gibi, istediğiniz kadar ek dosyayıda (attachments) maillarınız içerisinde gönderebilmenizi sağlıyor.

Uygulama tamamen JavaMail API ile geliştirildiğinden dolayı, gerekli olan kütüphaneleri geliştirme ortamınıza eklemeniz gerekiyor. javax.mail paketi altında gerekli olan tüm sınıflar toparlanmıştır. Bu kütüphane eğer geliştirme ortamınızda mevcut değil ise, buradan ulaşabilir, gerekli Jar dosyalarını bilgisayarınıza indirebilirsiniz.

Kod:
package org.javablog;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/*
* @author Fatih Mehmet Arslan
*/

public class SimpleMailSender
{
private String smtpHost; //Host
private String smtpAuthUser;
private String smtpAuthPassword;
private String mailBody;
private String mailSubject;
private String mailSender;

private String[] mailList;
private String[] attachmentFiles;

public SimpleMailSender(String host, String authUser,
String authPassword, String body, String subject,
String[] list, String sender, String[] files)
{
smtpHost = host;
smtpAuthUser = authUser;
smtpAuthPassword = authPassword;
mailBody = body;
mailSubject = subject;
mailSender = sender;
mailList = list;
attachmentFiles = files;

}

public **** sendMail() throws MessagingException
{
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");
//this property is required
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.host", smtpHost);
//required if SMTP server requires authentication
properties.put("mail.smtp.auth", "true");

Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(properties, auth);

//InternetAddress class represents an Internet email address
//Hence, lets model our email addresses

InternetAddress mailFrom = new InternetAddress(mailSender);
InternetAddress[] mailTo = new InternetAddress[mailList.length];

for(int i = 0; i < mailList.length; i++)
{
mailTo = new InternetAddress(mailList);
}

//Modeling an email message
//Message abstract class helps us to do this
//MimeMessage which extends Message class represents a MIME style email message
//We will represent entire email message in this form
//Let's create an instance

Message message = new MimeMessage(session);
message.setFrom(mailFrom);
message.setRecipients(Message.RecipientType.TO, mailTo);
message.setSubject(mailSubject);

/* Construct mail body parts */

Multipart multipart = new MimeMultipart();

//This represents message body part of mail
MimeBodyPart bodyPartMessage = new MimeBodyPart();
bodyPartMessage.setText(mailBody);

//Add first body part to multipart
multipart.addBodyPart(bodyPartMessage);

//This represents message attachment part
//will be added multipart later

MimeBodyPart bodyPartAttachment = new MimeBodyPart();;
FileDataSource fileDataSource;

for(int i = 0; i < attachmentFiles.length; i++)
{
fileDataSource = new FileDataSource(attachmentFiles);
bodyPartAttachment.setDataHandler(new DataHandler(fileDataSource));
bodyPartAttachment.setFileName(fileDataSource.getName());
//Add all attachment files to bodypart in multipart object
multipart.addBodyPart(bodyPartAttachment);
}

//Add entire mail body to the message object
message.setContent(multipart);

//Finally send the message
Transport.send(message);

}
//Testing our class
public static **** main(String[] args) throws MessagingException
{
String[] to = new String[2];
to[0] = "java@gmail.com";
to[1] = "mail@gmail.com";
String[] files = new String[2];
files[0] = "file1.txt";
files[1] = "file2.txt";

SimpleMailSender mailSender = new SimpleMailSender(
"smtp.gmail.com", "authUser@gmail.com", "authPassword", "Mail Body",
"Mail Subject", to, "sender@gmail.com",
files
);
mailSender.sendMail();
System.out.println("Mail has been sent successfully");
}

/*
* used to do simple authentication when the SMTP
* server requires it.
*/

private class SMTPAuthenticator extends Authenticator
{

public PasswordAuthentication getPasswordAuthentication() {
String username = smtpAuthUser;
String password = smtpAuthPassword;
return new PasswordAuthentication(username, password);
}
} //end of SMTPAuthenticator class

} // end of SimpleMailSender class
 
Üst