使用 unix sendmail 发送电子邮件 [英] Send email with unix sendmail

查看:52
本文介绍了使用 unix sendmail 发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是像 php mail 函数那样在 Unix 机器上发送电子邮件.在 StackOverflow 上,我已经找到了一个函数,但也许有人可以提出一个更优雅的解决方案,或者一个没有 fprintffwrite 的解决方案?因为我没有在我的 C++ 程序中使用 printf:

The goal is to send email on Unix machine like php mail function does. On StackOverflow I already found a function for doing it, but maybe somebody can suggest a more elegant solution or a solution without fprintf and fwrite? Because I do not use printf in my C++ program:

#include<stdio.h>
#include<errno.h>
int sendmail(const char *to, const char *from, const char *subject, const char *message)
{
    int retval = -1;
    FILE *mailpipe = popen("usr/lib/sendmail -t", "w");
    if (mailpipe != NULL)
    {
        fprintf(mailpipe, "To: %s\n", to);
        fprintf(mailpipe, "From: %s\n" from);
        fprintf(mailpipe, "Subject: %s\n\n", subject);
        fwrite(message, 1, strlen(message), mailpipe);
        fwrite(".\n", 1, 2, mailpipe);
        pclose(mailpipe);
        retval = 0;
     }
     else
     {
         perror("Failed to invoke sendmail");
     }
     return retval;
}

推荐答案

恕我直言,您只有两种方法可以做到这一点.首先是使用sendmail 子进程.在较低级别,您将通过管道与它通信,AFAIK 没有将 C++ 流关联到管道的标准方法.因此,您将不得不使用旧的 writefwritefprints 来输出数据.

IMHO you have only two ways of doing that. First is to use a sendmail subprocess. At a lower level, you will communicate with it through pipes and AFAIK there is no standard way to associate a C++ stream to a pipe. So you will have to use the good old write, fwrite or fprints to output your data.

另一种方法是直接打开一个到 smtp 服务器的套接字并使用 SMTP 协议(​​EHLO 或 HELO、MAIL FROM:、RCPT TO: DATA 和 BYE),处理服务器的响应......:-( 无论如何,没有更标准的方法可以从套接字创建 C++ 流!

The other way would be to directly open a socket to a smtp server and use the SMTP protocol (EHLO or HELO, MAIL FROM:, RCPT TO: DATA and BYE), dealing with the responses of the server ... :-( and anyway, there is no more standard way to create a C++ stream from a socket !

如果不想使用 fwrite 和 fprintf 的原因是不想使用 C 标准库,直接使用系统调用:用 C++ 字符串或 准备要发送的字符串strstream,直接用write将结果发送到管道.如果您也不想使用 write,只需问问自己 C++ 库如何写入文件...

If the reason why you do not want to use fwrite and fprintf is that you do not want to use the C standard library, directly use the system calls : prepare the strings to be sent with a C++ string or a strstream, and send the result to the pipe directly with write. And if you do not want to use write either, just ask yourself how does the C++ library write to files ...

这篇关于使用 unix sendmail 发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆