Labaratoriya ishi - 7 Mavzu: Elektron pochta tarmoq dasturini yaratish Bajardi: Jumayev Botir Tekshirdi: Berdimuradov Mirzohid
Mavzu: Elektron pochta tarmoq dasturini yaratish Ishning maqsadi: Talabalarda Java dasturlash tili javax.mail.* va java.util.* paketlari klasslaridan foydalanib elektron pochta bilan ishlovchi dastur yaratish bo‘yicha amaliy ko‘nikmalar hosil qilish. Nazariy qism: JavaMail API elektron pochta ilovalarini yaratishda platformaga bog‘liq bo‘lmagan va protokolga bog‘liq bo‘lmagan freymvorklarni qo‘llab quvvatlaydi. JavaMail API elektron pochta tizimini o‘z ichiga oluvchi obyektlarni aniqlovchi abstrakt klasslar to‘plamini ta’minlaydi. Bu elektron pochtani o‘qish, yozish va jo‘natish uchun paketdir. Quyida JavaMail APIda qo‘llab-quvvatlanadigan ba’zi protokollar keltirilgan: SMTP: Simple Mail Transfer Protocol. Elektron pochtani jo‘natish mexanizmini ta’minlaydi. POP3: Post Office Protocol. Elektron pochtani qabul qilish mexanizmini qo‘llab-quvvatlaydi. Har bir foydalanuvchiga bitta pochta qutisini qo‘llabquvvatlashni aniqlaydi. RFC 1939 ushbu protokolni aniqlaydi. IMAP4: Internet Message Access Protocol. Elektron pochtani qabul qilish mexanizmini qo‘llab-quvvatlaydigan mukammal protokoldir. Har bir foydalanuvchiga bir-nechta pochta qutilarini ta’minlaydi. Qo‘shimcha sifatida pochta qutisi bir-nechta foydalanuvchilarga taqsimlanishi mumkin. RFC 2060da aniqlangan. MIME: Multipurpose Internet Mail Extensions. Bu elektron pochtani ko‘chirish protokoli emas. Bu nima ko‘chirilayotganini, ya’ni elektron pochta tarkibi (formati, ilovalari)ni aniqlaydi. JavaMail API elektron pochtalarni yozish, qabul qilish va jo‘natish uchun qo‘llaniladi. 2 JavaMail API klasslari. JavaMail API elektron pochta xabarlarni jo‘natish, o‘qish va o‘chirishni amalgan oshiradigan ba’zi klasslarni o‘z ichiga oladi. JavaMail APIda tez-tez foydalanib turiladigan turiladigan ikkita javax.mail va javax.mail.internet paketlari mavjud. Ushbu paketlar JavaMailning asosiy klasslarini o‘z ichiga oladi. 7.1- jadval JavaMail API klasslari Klasslar Tavsifi javax.mail.Session APIning kalit klassi hisoblanadi. Bog‘lanishni namoyon etuvchi ko‘poqimli obyekt. javax.mail.Message Elektron pochta xabarini tadbiq etilishini ta’minlaydi. javax.mail.Address Xabarda manzillar bilan ishlashni ta’minlaydi. javax.mail.Authenticator Pochta serverida resurslarini ximoyalash uchun foydalaniladi javax.mail.Transport Elektron pochta xabarini jo‘natish mexanizmini ta’minlaydi. javax.mail.Store Xabarlarni saqlash va o‘qishni ta’minlaydi. Store papkalarga bo‘linadi. javax.mail.Folder Pochta xabarlarini papkalarda saqlashni ta’minlaydi. javax.mail.internet. MimeMessage Turli formatdagi elektron pochta xabarlari bilan ishlash imkoniyatini beradi. javax.mail.internet. InternetAddress RFC822 sintaksisidan foydalanib elektron pochta manzillari bilan ishlash imkonini beradi. Session klassi. Session klassi JavaMail APIning asosiy klassi hisoblanadi. Session obyekti sozlash va autentifikatsiya qilish maqsadida JavaMail API uchun bog‘lanishni yaratadi. Session obyekti quyidagi usullar bilan yaratilishi mumkin: - JNDI xizmatidan boshqariladigan obyektni qidirish orqali InitialContext ctx = new InitialContext(); Session session = (Session) ctx.lookup("usersMailSession"); 3 - Ikkinchi usul dasturlashga asoslangan java.util.Propertiesdan foydalanib Session obyekti yaratiladi. Session klassi konstruktori private hisoblanadi. Session klassi ikkita metodni ta’minlaydi: - getDefaultInstance():getDefaultInstance() metodidan goydalanib sukut bo‘yicha Session obyekti chaqiriladi. public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props,Authenticator auth) - getInstance(): getInstance() metodidan foydalanib yangi Session obyekti chaqiriladi. public static Session getInstance(Properties props) public static Session getInstance(Properties props,Authenticator auth) Message klassi Session obyekti yaratildi endi jo‘natiladigan xabarni yaratishga o‘tamiz. Xabar turi - Message abstrakt klass hisoblanadi, shuning uchun uning javax.mail.internet.MimeMessage klassi keng foydalaniladi. - Xabarni yaratish uchun MimeMessage konstruktoridan foydalaniladi. Misol uchun: MimeMessage message=new MimeMessage(session); - Xabar yaratildi. Endi xabarga ma’lumotlarni saqlashimiz lozim. Buning uchun message.setContent() yoki mimeMessage.setText() kabi metodlardan foydalanish mumkin. - Keng foydalaniladigan MimeMessage klassining metodlari 7.2- jadval MimeMessage klassining metodlari Metod Tavsifi public void setFrom(Address address) Jo‘natuvchining manzilini o‘rnatish uchun foydalaniladi public void addRecipients (Message.RecipientType type, String addresses) Qabul qiluvchilar turi va manzillarini aniqlaydi. public void setSubject(String subject) Mavzuni belgilash uchun 4 foydalaniladi. public void setText(String textmessage Xabar matnini belgilash uchun foydalaniladi. Address klassi. Session va Message obyektlariga egamiz, Address obyektidan foydalanib xabarga manzillarni qo‘shih lozim. - Address abstrakt klass hisoblanadi. Shuning uchun javax.mail.internet.InternetAddress klassi keng foydalaniladi. - Elektron pochta adresini qo‘yish bilan Address yaratiladi: Address address = new InternetAddress("talaba@gmail.com"); - Address obyektinin yaratishnin yana bitta yo‘li: Address address = new InternetAddress("talaba@gmail.com", asror); Authenticator klassi. Authenticator klassi tarmoq bog‘lanishi uchun autentifikatsiya qilish obyektini namoyon etadi. Odatda, ma’lumot uchun foydalanuvchidan so‘rovni amalga oshiradi. - Authenticator abstrakt klassi hisoblanadi. dan Login va parolni kiritish orqali PasswordAuthentication klassi konstruktoridan foydalanish mumkin. - Session obyekti yaratilayotganda Authenticatorni ro‘yxatdan o‘tqazish lozim. Quyida Authenticatorga misol keltirilgan: Properties props = new Properties(); PasswordAuthentication auth = new PasswordAuthentication("talaba", "parol") Session session = Session.getDefaultInstance(props, auth); Transport klassi Transport klassi xabarni ko‘chirish mexanizmida foydalaniladi. Odatda ushbu klass xabarni jo‘natishda SMTP protokolidan foydalaniladi. - static send() metodidan foydalanib xabarni jo‘natish mumkin: Transport.send(message); - ikkinchi yo‘li login va parol kiritish orqali sessiyani ochish, xabarni jo‘natish va bog‘lanishni yopish: 5 message.saveChanges(); // send() o‘rnida ishlatiladi //session uchun transportni belgilash Transport transport = session.getTransport("smtp"); //bog‘lanish transport.connect(host, username, password); //zarur bo‘lsa takrorlash transport.sendMessage(message, message.getAllRecipients()); //bajarildi, bog‘lanishni yopish transport.close(); Store klassi Xabarlarni saqlash va o‘qish uchun foydalaniladigan klass. Store klassi Service klassi yordamida kengaytiriladi. Store store = session.getStore("pop3"); store.connect(host, username, password); Folder klassi Folder klassi elektron pochta xabarlari uchun papkalarni namoyon etadi. Papkalar o‘z o‘rnida papkaostilarni va xabarlarni o‘z ichiga olishi mumkin. Storega bog‘langandan so‘ng Folderga murojaat qilish mumkin. Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); Folder obyektining getFolder(String name) metodi papkaosti nomini qaytaradi. Quyidagi rasmda Store va Folder bog‘lanishini ko‘rishimiz mumkin. Topshiriq: Talaba laboratoriya ishi uchun shaxsiy topshiriq oladi. Bu topshiriq bo‘yicha talaba elektron pochta bilan ishlovchi dastur yaratadi. Ishni bajarish tartibi: 1-qadam. Ish NetBeans IDE ishlab chiqarish muhitini yuklash bilan boshlanadi. Buning uchun ish stolida turgan NetBeans IDE muhiti yorlig‘ini sichqonchaning chap tomonini ikki marta bosib yuklanadi. Quyidagi rasmda NetBeans IDE muhitining asosiy darchasi yuklangan.
package uz.tatu;
import
java.net.*;
import java.io.*;
import java.util.*;
public class
server {
public static void main(String args[]) throws Exception {
ServerSocket soc = new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while (true) {
System.out.println("Waiting for Connection ...");
transferfile t = new transferfile(soc.accept());
}
}
}
class transferfile extends Thread {
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc) {
try {
ClientSoc = soc;
din = new DataInputStream(ClientSoc.getInputStream());
dout = new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
} catch (Exception ex) {
}
}
void SendFile() throws Exception {
String filename = din.readUTF();
File f = new File(filename);
if (!f.exists()) {
dout.writeUTF("File Not Found");
return;
} else {
dout.writeUTF("READY");
FileInputStream fin = new FileInputStream(f);
int ch;
do {
ch = fin.read();
dout.writeUTF(String.valueOf(ch));
}
while (ch != -1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
void ReceiveFile() throws Exception {
String filename = din.readUTF();
if (filename.compareTo("File not found") == 0) {
return;
}
File f = new File(filename);
String option;
out.println("Sending File ...");
FileInputStream fin = new FileInputStream(f);
int ch;
do {
ch = fin.read();
dout.writeUTF(String.valueOf(ch));
}
while (ch != -1);
fin.close();
System.out.println(din.readUTF());
public static void sendPlainTextEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// *** BEGIN CHANGE
properties.put("mail.smtp.user", userName);
// creates a new session, no Authenticator (will connect() later)
Session session = Session.getDefaultInstance(properties);
// *** END CHANGE
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// set plain text message
msg.setText(message);
// *** BEGIN CHANGE
// sends the e-mail
Transport t = session.getTransport("smtp");
t.connect(userName, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
// *** END CHANGE
public class SendAttachmentInEmail {
public static void main(String[] args) throws MessagingException {
sendPlainTextEmail("smtp.mail.ru", "587", "muhriddin.norqulov@mail.ru", "6S8dxF6APjDbrzBNaAGc", "berdimuradov.mirzohid@mail.ru", "Hello", "Hello, world!");
}
public static void sendPlainTextEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// *** BEGIN CHANGE
properties.put("mail.smtp.user", userName);
// creates a new session, no Authenticator (will connect() later)
Session session = Session.getDefaultInstance(properties);
// *** END CHANGE
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// set plain text message
msg.setText(message);
// *** BEGIN CHANGE
// sends the e-mail
Transport t = session.getTransport("smtp");
t.connect(userName, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
// *** END CHANGE