mail-cpp/main.cpp

110 lines
3.3 KiB
C++
Raw Normal View History

2024-07-23 22:12:01 +08:00
#include <iostream>
#include <string>
#include <Poco/Net/MailMessage.h>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/SecureSMTPClientSession.h>
#include <Poco/Net/NetException.h>
#include <Poco/Net/FilePartSource.h>
#include <Poco/Net/StringPartSource.h>
#include <Poco/Path.h>
#include <Poco/Zip/Compress.h>
#include <Poco/FileStream.h>
#include <Poco/File.h>
constexpr int port = 25;
constexpr auto sender{"taynpg@163.com"};
constexpr auto subject{"转tangjie收"};
constexpr auto attach_name{"转tangjie收.zip"};
constexpr auto smtp_server{ "smtp.163.com"};
bool compress(const Poco::Path& dirPath, std::string& out_file) {
// 获取目录路径的字符串表示
std::string dirStr = dirPath.toString();
// 构造压缩文件路径 /a/b/xx.zip
Poco::Path zipPath(dirPath);
Poco::Path parent_path = zipPath.parent();
parent_path.setFileName(attach_name);
// 获取压缩文件的字符串表示
out_file = parent_path.toString();
try {
// 检查压缩文件是否存在,如果存在则删除
Poco::File zipFileObj(out_file);
if (zipFileObj.exists()) {
std::cout << "存在同名压缩文件,删除中..." << std::endl;
zipFileObj.remove();
}
// 创建压缩文件的输出流
Poco::FileOutputStream zipStream(out_file);
// 创建压缩对象
Poco::Zip::Compress compress(zipStream, true); // true 表示递归压缩子目录
// 添加目录及其内容到压缩包
compress.addRecursive(dirStr, Poco::Zip::ZipCommon::CL_NORMAL);
// 关闭压缩流
compress.close();
std::cout << "压缩完成:" << out_file << std::endl;
return true;
} catch (Poco::Exception& e) {
std::cerr << "压缩过程中发生异常:" << e.displayText() << std::endl;
return false;
}
}
bool send(const std::string& file, const std::string& pwd, const std::string& recipient)
{
try {
Poco::Net::MailMessage message;
message.setSender(sender);
message.addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT, recipient));
message.setSubject(subject);
message.addContent(new Poco::Net::StringPartSource(subject), Poco::Net::MailMessage::ENCODING_8BIT);
auto file_content = new Poco::Net::FilePartSource(file, "application/zip");
message.addAttachment(attach_name, file_content);
Poco::Net::SecureSMTPClientSession smtp(smtp_server, port);
smtp.login(Poco::Net::SMTPClientSession::LoginMethod::AUTH_LOGIN, sender, pwd);
smtp.sendMessage(message);
smtp.close();
}
catch (Poco::Net::NetException& e) {
std::cerr << "error: " << e.displayText() << std::endl;
return false;
}
return true;
}
int main(int argc, char** argv)
{
if (argc != 4) {
std::cout << "first: dir_path, second:pwd, third: recipient." << std::endl;
return 0;
}
#if _WIN32
system("chcp 65001");
#endif
std::string out_file{};
if (!compress(argv[1], out_file)) {
return 0;
}
if (send(out_file, argv[2], argv[3])) {
std::cout << "Send Success." << std::endl;
}
else {
std::cout << "Send Failed." << std::endl;
}
return 0;
}