最近在完成一个邮箱代替的告警功能,写了一个邮件发送的demo
以下为代码:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include<QTcpSocket>
namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();//用来等待服务器响应void waitAndReadData();//功能函数void sendemil_fun();//登陆smtp服务器时所需的id和password,需要是base64编码格式QByteArray name;QByteArray passwd;//发送的标题和内容QByteArray s_Title;QByteArray s_Content;//发送邮件的邮件地址和接收地址,发送地址就是登陆的QByteArray sendemail;QByteArray rcvemail;private:Ui::MainWindow *ui;QTcpSocket *m_pSocket;QString m_receiverData;
};#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"#include<QString>
#include <QtNetwork>
#include<QtDebug>
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);m_pSocket=new QTcpSocket();//点击发送,获取所需参数,进行发送connect(ui->pushButton,&QPushButton::clicked,this,[=]{this->m_pSocket = new QTcpSocket;this->name = ui->logid_lineEdit->text().toUtf8().toBase64();this->passwd = ui->logpasswd_lineEidt->text().toUtf8().toBase64();this->sendemail = ui->SendEmail_lineEdit->text().toUtf8();this->rcvemail=ui->Rcvemail_lineEdit->text().toUtf8();m_receiverData = ui->subject_lineEdit->text().toUtf8();s_Content = ui->textEdit_Text->toPlainText().toUtf8();sendemil_fun();});}MainWindow::~MainWindow()
{delete ui;delete m_pSocket;}void MainWindow::waitAndReadData()
{m_pSocket->waitForReadyRead(1000);m_receiverData = m_pSocket->readAll();//将其显示在服务器反馈TextEdit中qDebug()<<m_receiverData<<endl;ui->server_textEdit->append(m_receiverData);
}void MainWindow::sendemil_fun()
{m_pSocket->connectToHost("smtp.qq.com",25,QTcpSocket::ReadWrite); //连接qq邮箱m_pSocket->waitForConnected(1000);waitAndReadData();m_pSocket->write("helo yuanzhaoyi\r\n");waitAndReadData();m_pSocket->write("auth login\r\n");waitAndReadData();m_pSocket->write(name+"\r\n"); //写入用户名waitAndReadData();m_pSocket->write(passwd+"\r\n"); //写入密码waitAndReadData();m_pSocket->write("mail from: <"+sendemail+">\r\n"); //发送的邮箱waitAndReadData();m_pSocket->write("rcpt to: <"+rcvemail+">\r\n"); //接收的邮箱waitAndReadData();m_pSocket->write("data\r\n"); //开始写入waitAndReadData();m_pSocket->write("from:<"+sendemail+">\r\n"); //发送名称waitAndReadData();m_pSocket->write("to:<"+rcvemail+">"); //接收名称waitAndReadData();m_pSocket->write("data\r\n");waitAndReadData();m_pSocket->write("Subject:"+s_Title+"\r\n"); //标题m_pSocket->write("\r\n");m_pSocket->write(s_Content.append("\r\n")); //内容m_pSocket->write(".\r\n");waitAndReadData();m_pSocket->write("quit\r\n");m_pSocket->disconnect();}