+7(960) 250-82-68 info@mirossa.ru


 mirossa        1С           C         PHP       JAVA  


Скр
 
 
кусок документации на русском: smtp_rfc2821.pdf

smtp. Отправка письма без вложения. + копия

//компиляция
//cd "C:\Program Files\Java\jdk1.8.0_151\bin"
//javac.exe MySmtp.java

//java.exe MySmtp

import java.net.*;
import java.io.*;
import javax.net.ssl.*;
import java.util.*;  // Base64
import java.nio.charset.StandardCharsets;
import java.text.*;

public class MySmtp{
	
	private static String[] get_data(BufferedReader in) throws Exception {
		
		String res = "";
		String inputLine;
		int l;
		String[] resAr = new String[4];
		
		while ((inputLine = in.readLine()) != null){
			res = res + inputLine + "\r\n";
			
			 l = inputLine.length();
			 if (l > 3){
				 if(inputLine.substring(3, 4).equals(" "))     //проверяем символ 4
					 break;
			 }else
				 break;
		}
		
		resAr[0] = res.substring(0, 1);
		resAr[1] = res.substring(1, 2);
		resAr[2] = res.substring(2, 3);
		resAr[3] = res;
		
		return resAr;
	}


	public static void main(String[] args) throws Exception {
        try {
            
			
			/////////////////////////////////////////////////////////////////
			
			Socket socket = new Socket("smtp.majordomo.ru", 587);
			
            
			
            
			PrintWriter out = new PrintWriter(
                                  new BufferedWriter(
                                  new OutputStreamWriter(
                                  socket.getOutputStream())));

 
            /* read response */
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    socket.getInputStream()));
			String inputLine;						
			byte[] decoded;
			String[] answer;
			
            if ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
			
			out.println("EHLO ddd");  //or out.print("EHLO ddd\r\n");
				// out.println("EHLO ddd\r\n");  -->>   554 SMTP synchronyzation error
			out.flush();
			answer = get_data(in);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			out.println("STARTTLS");
			out.flush();
			
			answer = get_data(in);
			
			///////////////////////////////////////////////////////
			
            // SSLSocket socket =
                // (SSLSocket)factory.createSocket("smtp.majordomo.ru", 587);
			
			SSLSocketFactory factory =
                 (SSLSocketFactory)SSLSocketFactory.getDefault();
			SSLSocket sslsocket = (SSLSocket) factory.createSocket(
			socket,
			socket.getInetAddress().getHostAddress(),
			socket.getPort(),
			true);
			sslsocket.startHandshake();
			
			PrintWriter out2 = new PrintWriter(
                                  new BufferedWriter(
                                  new OutputStreamWriter(
                                  sslsocket.getOutputStream())));

 
            /* read response */
            BufferedReader in2 = new BufferedReader(
                                    new InputStreamReader(
                                    sslsocket.getInputStream()));
									
			//////////////////////////////////////////////////////
			
			out2.println("EHLO ddd");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			out2.println("AUTH LOGIN");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("3")){   //334
				System.out.println(answer[3]);
				return;
			}
			
			out2.println(Base64.getEncoder().encodeToString("info@mirossa.ru".getBytes()));
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("3")){   //334
				System.out.println(answer[3]);
				return;
			}
			
			out2.println(Base64.getEncoder().encodeToString("password".getBytes()));
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //235
				System.out.println(answer[3]);
				return;
			}
			
			///////////////////////////////////////////////////
			Date dateNow = new Date();
			SimpleDateFormat formatForDateNow = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
			SimpleDateFormat formatForDateNow2 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);
			
			String header, text;
			Integer sizeMail;
			
			header = "Date: ".concat(formatForDateNow.format(dateNow).toString()).concat("\r\n");
			header = header.concat("From: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря".getBytes()))
							.concat("?= <info@mirossa.ru>\r\n");
			header = header.concat("X-Mailer: Mail client. (ver 1.1.1) Professional\r\n");
			header = header.concat("Reply-To: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря".getBytes()))
							.concat("?= <info@mirossa.ru>\r\n");
			header = header.concat("X-Priority: 3 (Normal)\r\n");
			header = header.concat("Message-ID: <131415666.").concat(formatForDateNow2.format(dateNow).toString())
							.concat("@mirossa.ru>\r\n");
			//header = header.concat("To: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря".getBytes()))
							//.concat("?= <info@mirossa.ru>\r\n");   //представление + адрес
			header = header.concat("Cc: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря 2".getBytes()))
							.concat("?= <info2@mirossa.ru>\r\n");   //представление + адрес
			header = header.concat("Subject: =?utf-8?B?"). concat(Base64.getEncoder().encodeToString("Тестовое письмо".getBytes()))
							.concat("?=\r\n");
			header = header.concat("MIME-Version: 1.0\r\n");
			header = header.concat("Content-Type: text/html; charset=utf-8\r\n");  // text/plain
			header = header.concat("Content-Transfer-Encoding: 8bit\r\n");

			text = "<html><body><p style=\"color: blue;\">Тестовое письмо.</p></body></html>";
			
			sizeMail = header.concat("\r\n").concat(text).getBytes("UTF-8").length;

			out2.println("MAIL FROM:<info@mirossa.ru> SIZE=".concat(Integer.toString(sizeMail)));
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			///////////////////////////////////////////////////
			
			out2.println("RCPT TO:<info@mirossa.ru>");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250   //251
				System.out.println(answer[3]);
				return;
			}
				
			out2.println("RCPT TO:<info2@mirossa.ru>");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250   //251
				System.out.println(answer[3]);
				return;
			}
			
			/////тело письма//////////////////////////////////////////////
			out2.print("DATA\r\n");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("3")){   //354
				System.out.println(answer[3]);
				return;
			}
			
			out2.print(header.concat("\r\n").concat(text).concat("\r\n.\r\n"));  
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			System.out.println("Email was successfully sent.");
			
			///////////////////////////////////////////////////
			out2.print("QUIT\r\n");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //221
				System.out.println(answer[3]);
				return;
			}
			
			
			in.close();  // ???
			out.close(); // ???           
			in2.close();
			out2.close();
			socket.close();  // ???
			sslsocket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

smtp. Отправка письма с прикрепленным файлом.

//компиляция
//cd "C:\Program Files\Java\jdk1.8.0_151\bin"
//javac.exe MySmtp2.java

//java.exe MySmtp2

import java.net.*;
import java.io.*;
import javax.net.ssl.*;
import java.util.*;  // Base64
import java.nio.charset.StandardCharsets;
import java.text.*;

public class MySmtp2{
		
	private static String[] get_data(BufferedReader in) throws Exception {
		
		String res = "";
		String inputLine;
		int l;
		String[] resAr = new String[4];
		
		while ((inputLine = in.readLine()) != null){
			res = res + inputLine + "\r\n";
			
			 l = inputLine.length();
			 if (l > 3){
				 if(inputLine.substring(3, 4).equals(" "))     //проверяем символ 4
					 break;
			 }else
				 break;
		}
		
		resAr[0] = res.substring(0, 1);
		resAr[1] = res.substring(1, 2);
		resAr[2] = res.substring(2, 3);
		resAr[3] = res;
		
		return resAr;
	}


	public static void main(String[] args) throws Exception {
        try {
            
			FileInputStream fin = new FileInputStream("C:\\Program Files\\Java\\jdk1.8.0_151\\bin\\qq.txt");
			
	/*		File fl = new File("C:\\Program Files\\Java\\jdk1.8.0_151\\bin\\qq.txt");
			System.out.println(fl.getName());  // "qq.txt"
			System.out.println(fl.getParent()); // "C:\Program Files\Java\jdk1.8.0_151\bin"
			System.out.println(fl.getAbsolutePath()); // "C:\Program Files\Java\jdk1.8.0_151\bin\qq.txt"    */
			
			/////////////////////////////////////////////////////////////////
			
			Socket socket = new Socket("smtp.majordomo.ru", 587);
			
            
			
            
			PrintWriter out = new PrintWriter(
                                  new BufferedWriter(
                                  new OutputStreamWriter(
                                  socket.getOutputStream())));

 
            /* read response */
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    socket.getInputStream()));
			String inputLine;						
			byte[] decoded;
			String[] answer;
			
            if ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
			
			out.println("EHLO ddd");  //or out.print("EHLO ddd\r\n");
				// out.println("EHLO ddd\r\n");  -->>   554 SMTP synchronyzation error
			out.flush();
			answer = get_data(in);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			out.println("STARTTLS");
			out.flush();
			
			answer = get_data(in);
			
			///////////////////////////////////////////////////////
			
            // SSLSocket socket =
                // (SSLSocket)factory.createSocket("smtp.majordomo.ru", 587);
			
			SSLSocketFactory factory =
                 (SSLSocketFactory)SSLSocketFactory.getDefault();
			SSLSocket sslsocket = (SSLSocket) factory.createSocket(
			socket,
			socket.getInetAddress().getHostAddress(),
			socket.getPort(),
			true);
			sslsocket.startHandshake();
			
			PrintWriter out2 = new PrintWriter(
                                  new BufferedWriter(
                                  new OutputStreamWriter(
                                  sslsocket.getOutputStream())));

 
            /* read response */
            BufferedReader in2 = new BufferedReader(
                                    new InputStreamReader(
                                    sslsocket.getInputStream()));
									
			//////////////////////////////////////////////////////
			
			out2.println("EHLO ddd");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			out2.println("AUTH LOGIN");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("3")){   //334
				System.out.println(answer[3]);
				return;
			}
			
			out2.println(Base64.getEncoder().encodeToString("info@mirossa.ru".getBytes()));
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("3")){   //334
				System.out.println(answer[3]);
				return;
			}
			
			out2.println(Base64.getEncoder().encodeToString("password".getBytes()));
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //235
				System.out.println(answer[3]);
				return;
			}
			
			///////////////////////////////////////////////////
			Date dateNow = new Date();
			SimpleDateFormat formatForDateNow = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
			SimpleDateFormat formatForDateNow2 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);
			
			String header, text;
			Integer sizeMail;
			
			header = "Date: ".concat(formatForDateNow.format(dateNow).toString()).concat("\r\n");
			header = header.concat("From: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря".getBytes()))
							.concat("?= <info@mirossa.ru>\r\n");
			header = header.concat("X-Mailer: Mail client. (ver 1.1.1) Professional\r\n");
			header = header.concat("Reply-To: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря".getBytes()))
							.concat("?= <info@mirossa.ru>\r\n");
			header = header.concat("X-Priority: 3 (Normal)\r\n");
			header = header.concat("Message-ID: <131415666.").concat(formatForDateNow2.format(dateNow).toString())
							.concat("@mirossa.ru>\r\n");
			header = header.concat("To: =?utf-8?B?").concat(Base64.getEncoder().encodeToString("Почта сектетаря".getBytes()))
							.concat("?= <info@mirossa.ru>\r\n");   //представление + адрес
			header = header.concat("Subject: =?utf-8?B?"). concat(Base64.getEncoder().encodeToString("Тестовое письмо".getBytes()))
							.concat("?=\r\n");
			header = header.concat("MIME-Version: 1.0\r\n");

/////основное отличие _нач///////			
			header = header.concat("Content-Type: multipart/mixed; boundary=\"b1d4ce5d-2857-4679-948c-cfa72fa94f86\"\r\n");
			
			text = "--b1d4ce5d-2857-4679-948c-cfa72fa94f86\r\n";
			text = text.concat("Content-Type: text/html; charset=utf-8\r\n");
			text = text.concat("Content-Transfer-Encoding: 8bit\r\n\r\n");
			
			text = text.concat("<html><body><p style=\"color: blue;\">Тестовое письмо.</p></body></html>"); //тело письма
			
			text = text.concat("\r\n--b1d4ce5d-2857-4679-948c-cfa72fa94f86\r\n");
			text = text.concat("Content-transfer-encoding: base64\r\n");
			text = text.concat("Content-Type: application/octet-stream; name=\"qq.txt\"\r\n");
			/*  "name=\"=?UTF-8?B?"..concat(Base64.getEncoder().encodeToString("Вопрос.txt".getBytes())).concat("?=\r\n") */
			text = text.concat("Content-Disposition: attachment; filename=\"qq.txt\"\r\n\r\n");
			
			
			byte[] buffer = new byte[fin.available()];
			fin.read(buffer, 0, fin.available());
			
			text = text.concat(Base64.getEncoder().encodeToString(buffer)); // данные прикрепленного файла
			
			text = text.concat("\r\n--b1d4ce5d-2857-4679-948c-cfa72fa94f86--");
			
/////основное отличие _кон////////
			
			sizeMail = header.concat("\r\n").concat(text).getBytes("UTF-8").length;

			out2.println("MAIL FROM:<info@mirossa.ru> SIZE=".concat(Integer.toString(sizeMail)));
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			///////////////////////////////////////////////////
			
			out2.println("RCPT TO:<info@mirossa.ru>");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250   //251
				System.out.println(answer[3]);
				return;
			}
				
						
			/////тело письма//////////////////////////////////////////////
			out2.print("DATA\r\n");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("3")){   //354
				System.out.println(answer[3]);
				return;
			}
			
			out2.print(header.concat("\r\n").concat(text).concat("\r\n.\r\n"));  
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //250
				System.out.println(answer[3]);
				return;
			}
			
			System.out.println("Email was successfully sent.");
			
			///////////////////////////////////////////////////
			out2.print("QUIT\r\n");
			out2.flush();
			answer = get_data(in2);
			if (!answer[0].equals("2")){   //221
				System.out.println(answer[3]);
				return;
			}
			
			
			in.close();  // ???
			out.close(); // ???           
			in2.close();
			out2.close();
			socket.close();  // ???
			sslsocket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}