POCO开源库发送邮件(局域网内)示例

本文提供了一个使用C++和POCO库在局域网内发送邮件的示例。通过命令行参数指定SMTP服务器地址、发件人和收件人,程序创建邮件,设置主题和内容,并添加附件,最后通过SMTPClientSession发送邮件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>

#include "Poco/Logger.h"
#include "Poco/FormattingChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FileChannel.h"
#include "Poco/Message.h"

#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailRecipient.h"
#include "Poco/Net/SMTPClientSession.h"
#include "Poco/Net/StringPartSource.h"
#include "Poco/Path.h"
#include "Poco/Exception.h"

using Poco::Logger;
using Poco::PatternFormatter;
using Poco::FormattingChannel;
using Poco::FileChannel;
using Poco::Message;

using Poco::Net::MailMessage;
using Poco::Net::MailRecipient;
using Poco::Net::SMTPClientSession;
using Poco::Net::StringPartSource;
using Poco::Path;
using Poco::Exception;

#pragma comment(lib,"PocoFoundationd.lib")
#pragma comment(lib,"PocoNetd.lib")

const unsigned char PocoLogo[] = 
{
	#include "PocoLogo.hpp"//图片的二进制文件,保存为.hpp格式
};

#define FILE_NAME "main.cpp"

//命令参数:sendMail.exe 192.180.10.208 xxx@spinfosec.com xxx@spinfosec.com
int main(int argc, char **argv)
{
	FormattingChannel *pFCFile = NULL;
	pFCFile = new FormattingChannel(new PatternFormatter("%Y-%m-%d %H:%M:%S.%c %U %u %N[%P]:%s:%q:%t"));
	pFCFile->setChannel(new FileChannel("./sample.log"));
	pFCFile->open();

	Logger &fileLogger = Logger::create("FileLogger", pFCFile, Message::PRIO_DEBUG);

	if (4 != argc)
	{
		Path p(argv[0]);
		fileLogger.error("usage:",FILE_NAME,49);
		fileLogger.error(p.getBaseName(),FILE_NAME,50);
		fileLogger.error("Send an email greeting from <sender> to <recipient>,using the SMTP server at <mailhost>.",FILE_NAME,51);
		return -1;
	}
	
	std::string mailHost(argv[1]);
	std::string sender(argv[2]);
	std::string recipient(argv[3]);
	
	fileLogger.debug(mailHost,FILE_NAME,61);
	fileLogger.debug(sender,FILE_NAME,62);
	fileLogger.debug(recipient,FILE_NAME,63);

	try
	{
		MailMessage message;
		message.setSender(sender);
		message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient));
		message.setSubject("Hello from the POCO C++ Libraries");
		std::string content;
		content += "Hello ";
		content += recipient;
		content += ",\r\n\r\n";
		content += "This is a greeting from the POCO C++ Libraries.\r\n\r\n";
		std::string logo(reinterpret_cast<const char*>(PocoLogo), sizeof(PocoLogo));
		message.addContent(new StringPartSource(content));
		message.addAttachment("logo", new StringPartSource(logo, "image/gif"));

		SMTPClientSession session(mailHost);
		session.open();
		session.login();
		session.sendMessage(message);
		session.close();
	}
	catch (Exception& exc)
	{
		fileLogger.error(exc.displayText(),FILE_NAME,88);
		return 1;
	}

	pFCFile->close();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值