qt之smtp-demo封装与测试

简介

      SMTP是一种提供可靠且有效的电子邮件传输的协议,它建立在FTP文件传输服务上的一种邮件服务,主要用于系统之间的邮件信息传递,并提供有关来信的通知。
      SMTP的工作过程是建立连接、邮件传送、连接释放。
      SMTP的默认端口是25。

二、SmtpClient-for-Qt库编译

1.链接库下载:

https://github.com/bluetiger9/SmtpClient-for-Qt

1.在qt工程上编译库:

qt之smtp-demo封装与测试_第1张图片

三、创建Demo工程,拷贝链接库和头文件到指定目录

qt之smtp-demo封装与测试_第2张图片
qt之smtp-demo封装与测试_第3张图片
qt之smtp-demo封装与测试_第4张图片
qt之smtp-demo封装与测试_第5张图片
qt之smtp-demo封装与测试_第6张图片

四、Demo工程核心代码

sendemail.h:

#ifndef SENDEMAIL_H
#define SENDEMAIL_H

#include 

typedef struct Email_Params_t
{
    QString sHost;
    int nPort;
    bool bSSL;
    bool bAuth;
    QString sUser;
    QString sPwd;
    QString Sender;
    QStringList sRecipients;
    QString Subject;
    QString sHtmlContent;
    QStringList Attachments;
}EMAIL_PARAM_T;

class SendEmail : public QObject
{
    Q_OBJECT
public:
    explicit SendEmail(QObject *parent = nullptr);
    ~SendEmail();

    static SendEmail& getInstance();

signals:
    void sig_returnMessage(QString sMessage);

public slots:
    void on_sendEmail(EMAIL_PARAM_T stEmailParam);

};

#endif // SENDEMAIL_H

sendemail.cpp:

#include "sendemail.h"
#include "SmtpMime"
#include "commondef.h"

SendEmail::SendEmail(QObject *parent)
{
    Q_UNUSED(parent)

}

SendEmail::~SendEmail()
{

}

SendEmail &SendEmail::getInstance()
{
    static SendEmail s_obj;
    return s_obj;
}

static EmailAddress stringToEmail(const QString & str)
{
    int p1 = str.indexOf("<");
    int p2 = str.indexOf(">");

    if (p1 == -1)
    {
        return EmailAddress(str);//no name, only email address
    }
    else
    {
        return EmailAddress(str.mid(p1 + 1, p2 - p1 - 1), str.left(p1));
    }
}

void SendEmail::on_sendEmail(EMAIL_PARAM_T stEmailParam)
{
    EmailAddress sender = stringToEmail(stEmailParam.Sender);
    SmtpClient smtp(stEmailParam.sHost, stEmailParam.nPort, stEmailParam.bSSL ? SmtpClient::SslConnection : SmtpClient::TcpConnection);

    MimeMessage message;
    message.setSender(stEmailParam.Sender);
    message.setSubject(stEmailParam.Subject);

    for(int i = 0; i < stEmailParam.sRecipients.size(); ++i)
    {
        message.addRecipient(stringToEmail(stEmailParam.sRecipients.at(i)));
    }

    MimeHtml content;
    content.setHtml(stEmailParam.sHtmlContent);
    message.addPart(&content);

    QList files;
    QList attachments;
    for(int i = 0; i < stEmailParam.Attachments.count(); ++i)
    {
        QFile* file = new QFile(stEmailParam.Attachments.at(i));
        files.append(file);

        MimeAttachment* attachment = new MimeAttachment(file);
        attachments.append(attachment);

        message.addPart(attachment);
    }

    smtp.connectToHost();
    if (!smtp.waitForReadyConnected())
    {
        emit sig_returnMessage("Connection Failed");
        MY_DEBUG << "Connection Failed";
        return;
    }

    if(stEmailParam.bAuth)
    {
        smtp.login(stEmailParam.sUser, stEmailParam.sPwd);
        if (!smtp.waitForAuthenticated())
        {
            emit sig_returnMessage("Authentification Failed");
            MY_DEBUG << "Authentification Failed";
            return;
        }
    }

    smtp.sendMail(message);
    if (!smtp.waitForMailSent())
    {
        emit sig_returnMessage("Mail sending failed");
        MY_DEBUG << "Mail sending failed";
        return;
    }
    else
    {
        emit sig_returnMessage("The email was succesfully sent.");
        MY_DEBUG << "The email was succesfully sent.";
    }

    smtp.quit();

    for (auto file : files)
    {
        delete file;
    }

    for (auto attachment : attachments)
    {
        delete attachment;
    }
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include "sendemail.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    void InitConfig();

signals:
    void sig_sendEmail(EMAIL_PARAM_T stEmailParam);

public slots:
    void on_recvMessage(QString sMessage);

private slots:
    void on_pushButton_AddAttachments_clicked();

    void on_pushButton_Send_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    InitConfig();

    //注册传递类型
    qRegisterMetaType("EMAIL_PARAM_T");
    connect(this, SIGNAL(sig_sendEmail(EMAIL_PARAM_T)),
            &SendEmail::getInstance(), SLOT(on_sendEmail(EMAIL_PARAM_T)));
    connect(&SendEmail::getInstance(), &SendEmail::sig_returnMessage,
            this, &MainWindow::on_recvMessage);

    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitConfig()
{
    ui->lineEdit_ServerAddress->setText("smtp.163.com");
    ui->lineEdit_Port->setText("25");

}

void MainWindow::on_recvMessage(QString sMessage)
{
    ui->textEdit_RecvMessage->setText(sMessage);
}

void MainWindow::on_pushButton_AddAttachments_clicked()
{
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::ExistingFiles);
    if(dialog.exec())
    {
        ui->listWidget_Attachments->addItems(dialog.selectedFiles());
    }
}

void MainWindow::on_pushButton_Send_clicked()
{
    EMAIL_PARAM_T emailParam;
    emailParam.sHost = ui->lineEdit_ServerAddress->text();
    emailParam.nPort = ui->lineEdit_Port->text().toInt();
    emailParam.bSSL = ui->checkBox_enableSSL->isChecked();
    emailParam.bAuth = ui->checkBox_ebableAuth->isChecked();
    emailParam.sUser = ui->lineEdit_User->text();
    emailParam.sPwd = ui->lineEdit_Pwd->text();

    emailParam.Sender = ui->lineEdit_Sender->text();
    emailParam.sRecipients = ui->lineEdit_Recviver->text().split(";");
    emailParam.Subject = ui->lineEdit_Subject->text();
    emailParam.sHtmlContent = ui->textEdit_Content->toHtml();

    for (int i = 0; i < ui->listWidget_Attachments->count(); ++i)
    {
        emailParam.Attachments.append(ui->listWidget_Attachments->item(i)->text());
    }

    emit sig_sendEmail(emailParam);
}


五、Demo工程测试结果:

1.注册163邮箱,开通服务

qt之smtp-demo封装与测试_第7张图片

2.填写邮件信息,点击发送

qt之smtp-demo封装与测试_第8张图片

六、Demo完整工程下载:

下载地址:https://download.csdn.net/download/linyibin_123/87347565

你可能感兴趣的:(qt,qt,开发语言)