ИПР2_В5 / Отчет ИПР2
.docxБЕЛОРУССКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ
ИНФОРМАТИКИ И РАДИОЭЛЕКТРОНИКИ
Кафедра программного обеспечения информационных технологий
Факультет ФКСиС
Специальность ПОИТ
Индивидуальная практическая работа №2
по дисциплине «Компьютерные системы и сети»
Вариант 5
Выполнил студент: Бордон Е.С.
группа 991051
Зачетная книжка № 99105004
Минск 2021
Условия задания
Написать программу, реализующую функции IMAP-клиента. В главном
окне клиента расположено поле типа memo, в котором отображается весь
протокол общения клиента с сервером. Тестирование программы-клиента производится при помощи любого стандартного почтового сервера, расположенного в сети Internet или локальной сети.
Программа должна позволять выводить, например список всех писем, а также текст отдельного письма. Отображение полученных данных в
форматированном виде не обязательно (можно в виде plain text).
Пояснения к работе программы
Программа реализована на языке программирования С++/CLI, в программной среде разработки Visual Studio 2019 с использованием windows forms. Программа выполняет функции IMAP клиента и позволяет просматривать входящую почту.
Рис 1. Рабочее окно программы
Весь процесс подключения и ошибки выводятся в поле memo. При подключении происходит процесс скачивания всех писем в созданную папку “inbox”. Список всех писем в этой папке отображен в поле listbox. Все скаченные письма имеют стандартное разрешение *.eml. Любое письмо можно открыть двойным кликом по листбоксу.
Для данной работы была создана тестовая почта на сервере mail.ru:
Сервер: imap.mail.ru
IMAP — 993 (протокол шифрования SSL/TLS)
ipr2bsuir_test@mail.ru
Yd3ThUEue3
Результат работы программы:
Рис2. Процесс удачного подключения
Рис 3. Пример открытого письма
Рис 4. Возможные ошибки подключения
Листинг программной части:
#include <tchar.h>
#include <winsock2.h>
#include <winsock.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <string.h>
#include <msclr\marshal.h>
#include "EAGetMailobj.tlh"
#include <algorithm>
namespace IPR2 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace msclr::interop;
using namespace EAGetMailObjLib;
using namespace System::IO;
using namespace System::Diagnostics;
/// <summary>
/// Сводка для MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TextBox^ textBox1;
protected:
private: System::Windows::Forms::TextBox^ textBox2;
private: System::Windows::Forms::TextBox^ textBox3;
private: System::Windows::Forms::TextBox^ textBox4;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::MenuStrip^ menuStrip1;
private: System::Windows::Forms::ToolStripMenuItem^ файлToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ выходToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ справкаToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ заданиеToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ обАвтореToolStripMenuItem;
private: System::Windows::Forms::ListBox^ listBox1;
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->textBox2 = (gcnew System::Windows::Forms::TextBox());
this->textBox3 = (gcnew System::Windows::Forms::TextBox());
this->textBox4 = (gcnew System::Windows::Forms::TextBox());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->label4 = (gcnew System::Windows::Forms::Label());
this->button1 = (gcnew System::Windows::Forms::Button());
this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
this->label5 = (gcnew System::Windows::Forms::Label());
this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());
this->файлToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->выходToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->справкаToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->заданиеToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->обАвтореToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
this->menuStrip1->SuspendLayout();
this->SuspendLayout();
//
// textBox1
//
this->textBox1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->textBox1->Location = System::Drawing::Point(150, 37);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(202, 29);
this->textBox1->TabIndex = 0;
this->textBox1->Text = L"imap.mail.ru";
//
// textBox2
//
this->textBox2->BackColor = System::Drawing::SystemColors::InactiveCaption;
this->textBox2->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->textBox2->Location = System::Drawing::Point(150, 93);
this->textBox2->Name = L"textBox2";
this->textBox2->ReadOnly = true;
this->textBox2->Size = System::Drawing::Size(202, 29);
this->textBox2->TabIndex = 1;
this->textBox2->Text = L"993";
//
// textBox3
//
this->textBox3->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->textBox3->Location = System::Drawing::Point(150, 151);
this->textBox3->Name = L"textBox3";
this->textBox3->Size = System::Drawing::Size(202, 29);
this->textBox3->TabIndex = 2;
this->textBox3->Text = L"ipr2bsuir_test@mail.ru";
//
// textBox4
//
this->textBox4->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->textBox4->Location = System::Drawing::Point(150, 209);
this->textBox4->Name = L"textBox4";
this->textBox4->Size = System::Drawing::Size(202, 29);
this->textBox4->TabIndex = 3;
this->textBox4->Text = L"Yd3ThUEue3";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label1->Location = System::Drawing::Point(12, 40);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(120, 21);
this->label1->TabIndex = 4;
this->label1->Text = L"IMAP-сервер:";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label2->Location = System::Drawing::Point(12, 96);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(132, 21);
this->label2->TabIndex = 5;
this->label2->Text = L"Порт SSL/TLS:\r\n";
//
// label3
//
this->label3->AutoSize = true;
this->label3->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label3->Location = System::Drawing::Point(12, 154);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(60, 21);
this->label3->TabIndex = 6;
this->label3->Text = L"Ящик:";
//
// label4
//
this->label4->AutoSize = true;
this->label4->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label4->Location = System::Drawing::Point(12, 212);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(73, 21);
this->label4->TabIndex = 7;
this->label4->Text = L"Пароль:";
//
// button1
//
this->button1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->button1->Location = System::Drawing::Point(16, 258);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(288, 38);
this->button1->TabIndex = 8;
this->button1->Text = L"Авторизоваться";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// richTextBox1
//
this->richTextBox1->BackColor = System::Drawing::SystemColors::Window;
this->richTextBox1->Font = (gcnew System::Drawing::Font(L"Courier New", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->richTextBox1->Location = System::Drawing::Point(381, 56);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->ReadOnly = true;
this->richTextBox1->Size = System::Drawing::Size(328, 240);
this->richTextBox1->TabIndex = 9;
this->richTextBox1->Text = L"";
//
// label5
//
this->label5->AutoSize = true;
this->label5->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label5->Location = System::Drawing::Point(377, 22);
this->label5->Name = L"label5";
this->label5->Size = System::Drawing::Size(195, 21);
this->label5->TabIndex = 10;
this->label5->Text = L"Процесс подключения:";
//
// menuStrip1
//
this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) {
this->файлToolStripMenuItem,
this->справкаToolStripMenuItem
});
this->menuStrip1->Location = System::Drawing::Point(0, 0);
this->menuStrip1->Name = L"menuStrip1";
this->menuStrip1->Size = System::Drawing::Size(730, 24);
this->menuStrip1->TabIndex = 11;
this->menuStrip1->Text = L"menuStrip1";
//
// файлToolStripMenuItem
//
this->файлToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->выходToolStripMenuItem });
this->файлToolStripMenuItem->Name = L"файлToolStripMenuItem";
this->файлToolStripMenuItem->Size = System::Drawing::Size(48, 20);
this->файлToolStripMenuItem->Text = L"Файл";
//
// выходToolStripMenuItem
//
this->выходToolStripMenuItem->Name = L"выходToolStripMenuItem";
this->выходToolStripMenuItem->Size = System::Drawing::Size(109, 22);
this->выходToolStripMenuItem->Text = L"Выход";
this->выходToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::выходToolStripMenuItem_Click);
//
// справкаToolStripMenuItem
//
this->справкаToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) {
this->заданиеToolStripMenuItem,
this->обАвтореToolStripMenuItem
});
this->справкаToolStripMenuItem->Name = L"справкаToolStripMenuItem";
this->справкаToolStripMenuItem->Size = System::Drawing::Size(65, 20);
this->справкаToolStripMenuItem->Text = L"Справка";
//
// заданиеToolStripMenuItem
//
this->заданиеToolStripMenuItem->Name = L"заданиеToolStripMenuItem";
this->заданиеToolStripMenuItem->Size = System::Drawing::Size(130, 22);
this->заданиеToolStripMenuItem->Text = L"Задание";
this->заданиеToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::заданиеToolStripMenuItem_Click);
//
// обАвтореToolStripMenuItem
//
this->обАвтореToolStripMenuItem->Name = L"обАвтореToolStripMenuItem";
this->обАвтореToolStripMenuItem->Size = System::Drawing::Size(130, 22);
this->обАвтореToolStripMenuItem->Text = L"Об авторе";
this->обАвтореToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::обАвтореToolStripMenuItem_Click);
//
// listBox1
//
this->listBox1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->listBox1->FormattingEnabled = true;
this->listBox1->ItemHeight = 19;
this->listBox1->Location = System::Drawing::Point(16, 320);
this->listBox1->Name = L"listBox1";
this->listBox1->Size = System::Drawing::Size(693, 156);
this->listBox1->TabIndex = 12;
this->listBox1->MouseDoubleClick += gcnew System::Windows::Forms::MouseEventHandler(this, &MyForm::listBox1_MouseDoubleClick);
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(730, 505);
this->Controls->Add(this->listBox1);
this->Controls->Add(this->label5);
this->Controls->Add(this->richTextBox1);
this->Controls->Add(this->button1);
this->Controls->Add(this->label4);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->textBox4);
this->Controls->Add(this->textBox3);
this->Controls->Add(this->textBox2);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->menuStrip1);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
this->MainMenuStrip = this->menuStrip1;
this->MaximizeBox = false;
this->Name = L"MyForm";
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"IMAP_client";
this->menuStrip1->ResumeLayout(false);
this->menuStrip1->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
DWORD _getCurrentPath(LPTSTR lpPath, DWORD nSize)
{
DWORD dwSize = ::GetModuleFileName(NULL, lpPath, nSize);
if (dwSize == 0 || dwSize == nSize)
{
return 0;
}
// Изменить имя файла на текущий полный путь
LPCTSTR psz = _tcsrchr(lpPath, _T('\\'));
if (psz != NULL)
{
lpPath[psz - lpPath] = _T('\0');
return _tcslen(lpPath);
}
return 0;
}
//Авторизироваться Кнопка!
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
const int MailServerImap4 = 1;
// Инициализировать среду COM
::CoInitialize(NULL);
// Создаем папку с именем "inbox" в текущей директории с исполняемым файлом.
// для сохранения полученных писем.
TCHAR szPath[MAX_PATH + 1];
_getCurrentPath(szPath, MAX_PATH);
TCHAR szMailBox[MAX_PATH + 1];
wsprintf(szMailBox, _T("%s\\inbox"), szPath);
// Создаем папку для хранения писем
::CreateDirectory(szMailBox, NULL);
// Удаляем сущестующие файлы в папке входящие INBOX если она уже есть
array<String^>^ files = Directory::GetFiles(Application::StartupPath, L"inbox\\*");
for (int i = 0; i < files->Length; i++) {
File::Delete("inbox\\" + Path::GetFileName(files[i]));
}
try
{
IMailServerPtr oServer = NULL;
oServer.CreateInstance(__uuidof(EAGetMailObjLib::MailServer));
marshal_context^ ctx = gcnew marshal_context(); // перевод из System::String^в const wchar_t* и с использованием marshal_context::marshal_as().
String^ now = textBox1->Text;
delete ctx;
oServer->Server = (ctx->marshal_as<const wchar_t*>(now));
//oServer->Server = ("imap.mail.ru");
marshal_context^ ctx1 = gcnew marshal_context();
String^ now1 = textBox3->Text;
delete ctx1;
oServer->User = (ctx->marshal_as<const wchar_t*>(now1));
//oServer->User = _T ("ipr2bsuir_test@mail.ru");
marshal_context^ ctx2 = gcnew marshal_context();
String^ now2 = textBox4->Text;
delete ctx2;
oServer->Password = (ctx->marshal_as<const wchar_t*>(now2));
//oServer->Password = _T ("Yd3ThUEue3");
oServer->Protocol = MailServerImap4;
// Включите SSL-соединение, большинство современных почтовых серверов требуют SSL / TLS по умолчанию
oServer->SSLConnection = VARIANT_TRUE;
/*Всегда по умолчанию
IMAP — 993 (протокол шифрования SSL/TLS)*/
oServer->Port = 993;
// Если ваш IMAP не развертывает SSL-соединение
// Пожалуйста, используйте
// oServer-> SSLConnection = VARIANT_FALSE;
// oServer-> Port = 143;
IMailClientPtr oClient = NULL;
oClient.CreateInstance(__uuidof(EAGetMailObjLib::MailClient));
oClient->LicenseCode = _T("TryIt");
oClient->Connect(oServer);
richTextBox1->AppendText (_T("Connected\r\n"));
IMailInfoCollectionPtr infos = oClient->GetMailInfoList();
//_tprintf(_T("Total %d emails\r\n"), infos->Count);
richTextBox1->AppendText(_T("Total emails ")+ infos->Count + "\r\n" + "\r\n");
for (long i = 0; i < infos->Count; i++)
{
IMailInfoPtr pInfo = infos->GetItem(i);
TCHAR szFile[MAX_PATH + 1];
// Генерация случайного имени файла по текущей локальной дате и времени,
// Вы можете использовать свой метод для генерации имени файла, если оно вам не нравится
SYSTEMTIME curtm;
::GetLocalTime(&curtm);
::wsprintf(szFile, _T("%s\\%04d%02d%02d%02d%02d%02d%03d%d.eml"),
szMailBox,
curtm.wYear,
curtm.wMonth,
curtm.wDay,
curtm.wHour,
curtm.wMinute,
curtm.wSecond,
curtm.wMilliseconds,
i);
// Получение электронной почты от сервера
IMailPtr oMail = oClient->GetMail(pInfo);
// Сохраняем электронную почту на локальный диск
oMail->SaveAs(szFile, VARIANT_TRUE);
// НЕ УДАЛЯЕМ С СЕРВЕРА
// Пометить электронную почту как удаленную с сервера
// oClient->Delete(pInfo);
}
// Метод удаления просто помечаем письмо как удаленное,
// Метод выхода точно удаляет электронные письма с сервера.
oClient->Quit();
}
catch (_com_error& ep)
{
const TCHAR* message = ep.Description();
String^ errors;
errors = marshal_as<String^>(message);
richTextBox1->AppendText(_T("Error: ") + errors + "\r\n");
}
// Выводим список писем в листбокс
listBox1->Items->Clear();
array<String^>^ filess = Directory::GetFiles(Application::StartupPath, L"inbox\\*");
for (int i = 0; i < filess->Length; i++) {
listBox1->Items->Add(Path::GetFileName(filess[i]));
}
}
private: System::Void выходToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
Close();;
}
private: System::Void заданиеToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
String^ message = "Написать программу, реализующую функции IMAP-клиента. В главном " +
"окне клиента расположено поле типа memo, в котором отображается весь " +
"протокол общения клиента с сервером.Тестирование программы - клиента производится при помощи любого " +
"стандартного почтового сервера, расположенного в сети Internet или локальной " +
"сети." + "\r\n" +
"Программа должна позволять выводить, например список всех писем, а " +
"также текст отдельного письма.Отображение полученных данных в " +
"форматированном виде не обязательно(можно в виде plain text).";
MessageBox::Show(message, "Вариант 5", MessageBoxButtons::OK);
}
private: System::Void обАвтореToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
String^ message = "Выполнил студент: Бордон Е.С." + "\r\n" + "Группа 991051" + "\r\n" + "Зачетная книжка № 99105004";
MessageBox::Show(message, "ИПР_2", MessageBoxButtons::OK);
}
private: System::Void listBox1_MouseDoubleClick(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
// Открытие письма из листбокса
Process::Start("inbox\\" + Convert::ToString(listBox1->Text));
}
};
}