c 언어로 메일보내는 소스입니다.

leesunghee47의 이미지

안녕하세요. 현재 장비에서 mail를 보내야 하는데 어떻게 해야 할지.. 몰라.. 이렇게 글 올립니다

구글링을 해보니 sendmail를 사용해서 하라고 해서 사용중인 busybox ( 1.13.4 )에서 sendmail를 이용해서 해 보려는데요..
어떻게 해야 할지 모르겠네요.. 구글에서 검색해보면 서버 아이디 패스워드 등을 넣는 옵션이 있는데 현재 sendmail를 보면
옵션이 이게 다입니다.

BusyBox v1.13.4 (2014-10-23 04:01:34 PDT) multi-call binary
 
Usage: sendmail [OPTIONS] [rcpt]...
 
Send an email
 
Options:
        -w timeout      Network timeout
        -H [user:pass@]server[:port] Server
        -S              Use openssl connection helper for secure servers
        -N type         Request delivery notification. Type is ignored
        -f sender       Sender
        -F fullname     Sender full name. Overrides $NAME
        -s subject      Subject
        -j charset      Assume charset for body and subject (us-ascii)
        -a file         File to attach. May be multiple
        -H "prog args..." Use external connection helper. E.g. openssl for secure servers
        -S server[:port] Server
        -c rcpt         Cc: recipient. May be multiple
        -e rcpt         Errors-To: recipient

어떻게... 해야 할까요..

그리고 아래는 구글 검색하다보니 메일 보내는 소스가 있어서 이것도 해보니 에러가 뜨는데요.. 일단 smtp 서버는 kornrt.net를 이용했습니다.

./mail -S kornet.net -s 메일제목 -r 수신자 메일내용.txt

이렇게 하니

kornet.net --> 220 relay10.kornet.net ESMTP Terrace MailWatcher 5.40.2008012515 (for kornet.net)
kornet.net --> 550 5.1.8 you are not allowed to send mail.
unexpected reply: 550 5.1.8 you are not allowed to send mail.

이렇게 에러메시지가 뜹니다.. 권한이 없다는데.. 아마도 kornet.net 아이디와 패스워드를 넣어줘야 하는데..
어떻게 수정을해야.. 아이디와 패스워드를 넣어줄수 있을까요?

아래는 소스입니다.

보시고.. 답변좀 부탁드려요 ㅜㅜ..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <getopt.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
 
static char *from_addr  = NULL;                /* 보내는 사람 주소        */
static char *reply_addr = NULL;                /* 받는 사람 주소        */
static char *mailhost   = NULL;                /* 메일서버 주소        */
static int   mailport   = 25;                /* 메일서버 포트        */
static char *subject    = 0;                /* 메일 제목                 */
static FILE *sfp;
static FILE *rfp;
 
/*
** 메일서버에서 응답받기
*/
void Get_Response(void)
{
    char buf[BUFSIZ];
 
    while (fgets(buf, sizeof(buf), rfp)) {
        buf[strlen(buf)-1] = 0;
                /*
        printf("%s --> %s\n", mailhost, buf);
                */
        if (!isdigit(buf[0]) || buf[0] > '3') {
            printf("unexpected reply: %s\n", buf);
            exit(-1);
        }
        if (buf[4] != '-')
            break;
    }
    return;
}
 
/*
** 메일서버로 내용 전송하고 응답받기
*/
void Chat(char *fmt, ...)
{
    va_list ap;
 
    va_start(ap, fmt);
    vfprintf(sfp, fmt, ap);
    va_end(ap);
 
        /*
    va_start(ap, fmt);
    printf("%s <-- \n", mailhost);
    vprintf(fmt, ap);
    va_end(ap);
        */
 
    fflush(sfp);
    Get_Response();
}
 
/*
**  main 함수
*/
 
void Usage(void)
{
        printf("\n");
        printf("usage   : cymail [-S host] [-s subject] <-r reply-addr> FILE\n");
        printf("options :\n");
        /*
        printf("  -S, --smtp-host=HOST        host where MTA can be contacted via SMTP\n")
        */
        printf("          -S,       host where MTA can be contacted via SMTP\n");
        printf("          -s,       subject line of message\n");
        printf("          -r,       address of the sender for replies\n");
        printf("\n");
        exit(0);
}
 
int main(int argc, char **argv)
{
        FILE *fpFile;
    char buf[BUFSIZ];
    char my_name[BUFSIZ];
    struct sockaddr_in sin;
    struct hostent *hp;
    struct servent *sp;
        int c;
    int s;
    int r;
    char *cp;
 
        opterr = 0;
 
        while((c = getopt(argc, argv, "S:s:r:")) != -1)
        {
                switch(c)
                {
                        case 'S':
                                mailhost = optarg;
                                break;
                        case 's':
                                subject = optarg;
                                break;
                        case 'r':
                                from_addr = optarg;
                                reply_addr = optarg;
                                break;
                        case '?':
                                Usage();
                                exit(-1);
                }
        }
 
        if (mailhost == NULL)
        {
                if ((cp = getenv("SMTPSERVER")) != NULL)
                {
                        mailhost = cp;
                }
                else
                {
                        printf("SMTPSERVER is not setting\n");       
                        exit(-1);
                }
        }
 
        if( optind != (argc -1))
        {
                Usage();
                exit(-1);
        }
 
        if(from_addr == NULL)
        {
                Usage();
                exit(-1);
        }
 
    /*
     *  메일 서버에 연결
     */
 
    if ((hp = gethostbyname(mailhost)) == NULL) {
        printf("%s: unknown host\n", mailhost);
        exit(-1);
    }
    if (hp->h_addrtype != AF_INET) {
        printf("unknown address family: %d\n", hp->h_addrtype);
        exit(-1);
    }
 
    memset((char *)&sin, 0, sizeof(sin));
    memcpy((char *)&sin.sin_addr, hp->h_addr, hp->h_length);
 
    sin.sin_family = hp->h_addrtype;
    sin.sin_port = htons(mailport);
 
    if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("socket: error\n");
        exit(-1);
    }
    if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
        printf("connect: error\n");
        exit(-1);
    }
    if ((r = dup(s)) < 0) {
        printf("dup: error\n");
        exit(-1);
    }
    if ((sfp = fdopen(s, "w")) == 0) {
        printf("fdopen: error\n");
        exit(-1);
    }
    if ((rfp = fdopen(r, "r")) == 0) {
        printf("fdopen: error\n");
        exit(-1);
    }
 
    /* 
     *  SMTP 헤더보내기
     */
    Get_Response(); /* 초기 메시지 받기 */
        /*
    Chat("HELO %s\r\n", my_name);
        */
    Chat("MAIL FROM: <%s>\r\n", from_addr);
    Chat("RCPT TO: <%s>\r\n", reply_addr);
    Chat("DATA\r\n");
 
    /* 
     *  메일 제목
     */
        if( subject != NULL)
        {
            fprintf(sfp, "Subject: %s\r\n", subject);
            fprintf(sfp, "\r\n");
    }
 
    /* 
     *  메일 내용 읽기
     */
        if ((fpFile = fopen(argv[argc - 1], "r")) == NULL )
        {
                printf("no message file \n");
                exit(-1);
        }
        else
        {
                while(fgets(buf, sizeof(buf), fpFile))
                {
                        buf[strlen(buf)-1] = 0;
                        if (strcmp(buf, ".") == 0)
                        {
                                fprintf(sfp, ".\r\n");
                        }
                        else
                        {
                                fprintf(sfp, "%s\r\n", buf);
                        }
                }
                fclose(fpFile);
        }
 
    /* 
     *  내용 종료 및 통신 종료
     */
    Chat(".\r\n");
    Chat("QUIT\r\n");
 
        printf("Your mail is sended successfully !!\n");
    exit(0);
}
김정균의 이미지

일단 코드 정리해 드렸고요.

코드를 보니, 자기 자신이 자신의 계정에 메일을 보내는 방식이군요. (To와 From이 동일한 형태..)
아마도 kornet 서버의 spam 체크 룰에 걸린 듯 싶습니다. 그리고 요즘 포털에 메일을 보내려면 white ip 조건도 성립을 해야 하고 챙길 것 들이 꽤 있습니다.

그러므로, white ip 등록도 해야할 수도 있고, 메일을 보내는 IP의 inverse domain 설정이 필요할 수도 있고, DKIM, SPF등의 설정이 필요할 수도 있고, 정상적으로 들어오는 헤더들을 참고해야 할 수도 있고 등등 챙겨야할 것들이 상당히 많이 있습니다.

그리고, 메일 발송하는 프로그램을 만들어야 한다면, 메일 전송 protocol에 대해서 먼저 알아보시는 것이 문제를 해결할 수 있겠죠. 제가 보기에는 코드를 짤줄 모르는 문제가 아니라, 프로토콜을 모르기 때문에 무얼 수정해야 하는지 모르는 듯 싶습니다.

http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Network_Programing/Documents/SMTP

문서라도 참조해 보시지요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.