最近在完成一个邮箱代替的告警功能,写了一个邮件发送的demo
以下为代码:
cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
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
cpp
#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();
//此程序发送邮件作为主线程,会堵塞窗口,可以根据情况来使用子线程来运行,demo先使用主线程来完成邮件发送
//点击发送,获取所需参数,进行发送
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();
}