用Tcl发送MIME邮件

风行水上 @ 2013-09-21 16:05:39
标签:

    正好有人问起,如果要用Tcl语言发送多媒体(MIME)邮件,基本代码如下:

    set message {
      <h1>标题</h1>
      <b>粗体</b>
      <p style="color:red">红色</p>
    }
    
    set charset [encoding system]
    set message [encoding convertto $charset $message]
    set to    "[email protected]"
    set from  "[email protected]"
    set subject "Hello"
    
    package require mime
    
    set m [mime::initialize -canonical "text/html; charset=$charset" \
      -header [list From $from] \
      -header [list To $to] \
      -header [list Subject $subject] \
      -encoding  base64  \
      -string $message]
    
    
    set data [mime::buildmessage $m]
    
    exec sendmail -t << $data
    

    多媒体邮件的关键点有三点:

    1. 基于MIME协议
    2. 传输编码(Content-Transfer-Encoding):用于传输二进制数据,常用的有BASE64编码。
    3. 内容编码:即Content-Type中指定的编码

    上面代码中的MIME处理包mime可以从tcllib中获得。

    标题(Subject)中的字符编码

    邮件的Subject是header的一部分,根据协议要求,只允许ASCII字符。因此对于中文字符需要特别的编码

    Subject: =?gb2312?B?中文字符的baset64编码?=

    上面的?B?指明使用base64编码;如果是?Q?的话,则指的是quoted-printable编码。

    如果是quoted-printable编码,字符'?'和'='不能直接使用,'_'则被解释为空格' '。

    附件的处理

    如果要包含附件,则需要进一步了解 multipart 协议。

    MIME-Version: 1.0
    Content-Type: multipart/mixed; boundary=frontier
    
    This is a message with multiple parts in MIME format.
    --frontier
    Content-Type: text/plain
    
    This is the body of the message.
    --frontier
    Content-Type: application/octet-stream
    Content-Transfer-Encoding: base64
    
    PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg
    Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==
    --frontier--
    

    网络资源

    标签:

      分享到:
      comments powered by Disqus

      25/29ms