2014-12-06 31 views
1

如何通過使用c套接字的postfix發送電子郵件? 如何創建消息proggramly如何通過使用c套接字的postfix發送電子郵件?

struct sockaddr_in addr; 
char message[] = "MAIL From: [email protected]\n \"[email protected]\"\n\"Test mail\"\n\"This is a test email\""; 
char buf[512]; 
//creating socket 

int sock = socket(AF_INET, SOCK_DGRAM , 0); 
//address parameters 

addr.sin_family = AF_INET; 
//connection port 
addr.sin_port = htons(8); 

// Inet 127.0.0.1. 
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); 

sendto(sock, message, sizeof(message), 0, (struct sockaddr *)&addr, sizeof(addr)); 
close(sock); 
+0

這不是一個答案,因此我會把在這裏;我想建議使用實際庫發送郵件intead。 – LyingOnTheSky 2014-12-06 23:05:35

+0

是的,庫是好的,我的任務是使用套接字 – 2014-12-06 23:07:47

+0

哎呀我沒明白,* postfix *是庫,沒關係。 – LyingOnTheSky 2014-12-06 23:10:23

回答

-1

找到解決方案

#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <string.h> 

int main(int argc, char** argv) 
{ 
    int i; 
    struct sockaddr_in addr; 
    //commands for server 
    char* commands[] = {"eclo localhost\n", "mail from:[email protected]\n", "rcpt to:[email protected]\n", "data\n", "Subject: Тест\n\nТест\n", "\n.\n", "quit\n"}; 



    //creating socket 
    int sock = socket(AF_INET, SOCK_STREAM , 0); 
    if(sock < 0) 
    { 
     perror("error with creation of socket"); 
     return -errno; 
    } 

    //parameters 
    addr.sin_family = AF_INET; 
    //port 25 
    addr.sin_port = htons(25); 

    // Inet 127.0.0.1. 
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); 

    //connecting to server 
    if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) 
    { 
    perror("error with creation of socket"); 
     return -errno; 
    } 

    //sending commands 
    for(i = 0; i < sizeof(commands)/4; i++) 
     send(sock, commands[i], strlen(commands[i]), 0); 

    //closing connection 
    close(sock); 

    return (EXIT_SUCCESS); 
} 
+0

這些命令部分錯誤(「eclo」而不是「ehlo」,「\ n」而不是「\ r \ n」等),並且您甚至沒有檢查服務器的響應。這隻適用於寬容服務器,其他人可能會拒絕發送,甚至可能將您的IP列爲垃圾郵件發送者。請查看[SMTP協議](http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol)瞭解如何完成此操作。 – 2014-12-07 07:04:37

相關問題