如何使用 Linux 命令行将文件作为电子邮件附件发送?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:21:36  来源:igfitidea点击:

How do I send a file as an email attachment using Linux command line?

linuxemailcommand-line

提问by Kit Roed

I've created a script that runs every night on my Linux server that uses mysqldumpto back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to mailxlike so:

我创建了一个脚本,它每晚都在我的 Linux 服务器上运行,用于mysqldump将我的每个 MySQL 数据库备份到 .sql 文件,并将它们打包为一个压缩的 .tar 文件。我要完成的下一步是通过电子邮件将该 tar 文件发送到远程电子邮件服务器以进行妥善保管。我已经能够通过管道备份文本文件mailx像这样发送正文中的原始脚本电子邮件:

$ cat mysqldbbackup.sql | mailx [email protected]

catechoes the backup file's text which is piped into the mailxprogram with the recipient's email address passed as an argument.

cat回显备份文件的文本,该文本通过管道传输到mailx程序中,并将收件人的电子邮件地址作为参数传递。

While this accomplishes what I need, I think it could be one step better, Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an attachment?This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.

虽然这完成了我所需要的,但我认为这可能会更好,有没有办法,使用 shell 脚本或其他方式,将压缩的 .tar 文件作为附件发送到外发电子邮件?这将胜过必须处理包含标题数据且通常具有自动换行问题等的非常长的电子邮件。

采纳答案by rynop

None of the mutt ones worked for me. It was thinking the email address was part of the attachemnt. Had to do:

没有一个笨蛋对我有用。它认为电子邮件地址是附件的一部分。不得不做:

echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- [email protected]

回答by Chris N

From looking at man mailx, the mailx program does not have an option for attaching a file. You could use another program such as mutt.

从查看来看man mailx,mailx 程序没有附加文件的选项。您可以使用其他程序,例如 mutt。

echo "This is the message body" | mutt -a file.to.attach -s "subject of message" [email protected]

Command line options for mutt can be shown with mutt -h.

mutt 的命令行选项可以用mutt -h.

回答by David Schlosnagle

You can use muttto send the email with attachment

您可以使用mutt发送带有附件的电子邮件

mutt -s "Backup" -a mysqldbbackup.sql [email protected] < message.txt

回答by Nathan Fellman

Depending on your version of linux it may be called mail. To quote @David above:

根据您的 linux 版本,它可能被称为邮件。引用上面的@David:

mail -s "Backup" -a mysqldbbackup.sql [email protected] < message.txt

or also:

或者:

cat message.txt | mail -s "Backup" -a mysqldbbackup.sql [email protected] 

回答by Daniel Fone

Or, failing mutt:

或者,失败的笨蛋:

gzip -c mysqldbbackup.sql | uuencode mysqldbbackup.sql.gz  | mail -s "MySQL DB" [email protected]

回答by Gunstick

metamail has the tool metasend

metamail 有工具 metasend

metasend -f mysqlbackup.sql.gz -t [email protected] -s Backup -m application/x-gzip -b

回答by Gunstick

I use mpack.

我用mpack。

mpack -s subject file [email protected]

Unfortunately mpack does not recognize '-' as an alias for stdin. But the following work, and can easily be wrapped in an (shell) alias or a script:

不幸的是,mpack 无法将“-”识别为 stdin 的别名。但是下面的工作,可以很容易地包装在(shell)别名或脚本中:

mpack -s subject /dev/stdin [email protected] < file

回答by glenn Hymanman

I once wrote this function for ksh on Solaris (uses Perl for base64 encoding):

我曾经在 Solaris 上为 ksh 编写过这个函数(使用 Perl 进行 base64 编码):

# usage: email_attachment to cc subject body attachment_filename
email_attachment() {
    to=""
    cc=""
    subject=""
    body=""
    filename="${5:-''}"
    boundary="_====_blah_====_$(date +%Y%m%d%H%M%S)_====_"
    {
        print -- "To: $to"
        print -- "Cc: $cc"
        print -- "Subject: $subject"
        print -- "Content-Type: multipart/mixed; boundary=\"$boundary\""
        print -- "Mime-Version: 1.0"
        print -- ""
        print -- "This is a multi-part message in MIME format."
        print -- ""
        print -- "--$boundary"
        print -- "Content-Type: text/plain; charset=ISO-8859-1"
        print -- ""
        print -- "$body"
        print -- ""
        if [[ -n "$filename" && -f "$filename" && -r "$filename" ]]; then
            print -- "--$boundary"
            print -- "Content-Transfer-Encoding: base64"
            print -- "Content-Type: application/octet-stream; name=$filename"
            print -- "Content-Disposition: attachment; filename=$filename"
            print -- ""
            print -- "$(perl -MMIME::Base64 -e 'open F, shift; @lines=<F>; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)"
            print -- ""
        fi
        print -- "--${boundary}--"
    } | /usr/lib/sendmail -oi -t
}

回答by Mike Graf

Just to add my 2 cents, I'd write my own PHP Script:

只是为了增加我的 2 美分,我会编写自己的 PHP 脚本:

http://php.net/manual/en/function.mail.php

http://php.net/manual/en/function.mail.php

There are lots of ways to do the attachment in the examples on that page.

有很多方法可以在该页面上的示例中执行附件。

回答by user1651561

Send a Plaintext body email with one plaintext attachment with mailx:

使用 mailx 发送带有一个纯文本附件的纯文本正文电子邮件:

(
  /usr/bin/uuencode attachfile.txt myattachedfilename.txt; 
  /usr/bin/echo "Body of text"
) | mailx -s 'Subject' [email protected]

Below is the same command as above, without the newlines

下面是与上面相同的命令,没有换行符

( /usr/bin/uuencode /home/el/attachfile.txt myattachedfilename.txt; /usr/bin/echo "Body of text" ) | mailx -s 'Subject' [email protected]

Make sure you have a file /home/el/attachfile.txtdefined with this contents:

确保您有一个/home/el/attachfile.txt使用以下内容定义的文件:

<html><body>
Government discriminates against programmers with cruel/unusual 35 year prison
sentences for making the world's information free, while bankers that pilfer 
trillions in citizens assets through systematic inflation get the nod and 
walk free among us.
</body></html>

If you don't have uuencode read this: https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work

如果您没有 uuencode,请阅读:https: //unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work

On Linux, Send HTML body email with a PDF attachment with sendmail:

在 Linux 上,使用 sendmail 发送带有 PDF 附件的 HTML 正文电子邮件:

Make sure you have ksh installed: yum info ksh

确保你已经安装了 ksh: yum info ksh

Make sure you have sendmail installed and configured.

确保您已安装并配置了 sendmail。

Make sure you have uuencode installed and available: https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work

确保您已安装并可用 uuencode:https: //unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work

Make a new file called test.shand put it in your home directory: /home/el

创建一个名为的新文件test.sh并将其放在您的主目录中:/home/el

Put the following code in test.sh:

将以下代码放入test.sh

#!/usr/bin/ksh
export MAILFROM="[email protected]"
export MAILTO="[email protected]"
export SUBJECT="Test PDF for Email"
export BODY="/home/el/email_body.htm"
export ATTACH="/home/el/pdf-test.pdf"
export MAILPART=`uuidgen` ## Generates Unique ID
export MAILPART_BODY=`uuidgen` ## Generates Unique ID

(
 echo "From: $MAILFROM"
 echo "To: $MAILTO"
 echo "Subject: $SUBJECT"
 echo "MIME-Version: 1.0"
 echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
 echo ""
 echo "--$MAILPART"
 echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
 echo ""
 echo "--$MAILPART_BODY"
 echo "Content-Type: text/plain; charset=ISO-8859-1"
 echo "You need to enable HTML option for email"
 echo "--$MAILPART_BODY"
 echo "Content-Type: text/html; charset=ISO-8859-1"
 echo "Content-Disposition: inline"
 cat $BODY
 echo "--$MAILPART_BODY--"

 echo "--$MAILPART"
 echo 'Content-Type: application/pdf; name="'$(basename $ATTACH)'"'
 echo "Content-Transfer-Encoding: uuencode"
 echo 'Content-Disposition: attachment; filename="'$(basename $ATTACH)'"'
 echo ""
 uuencode $ATTACH $(basename $ATTACH)
 echo "--$MAILPART--"
) | /usr/sbin/sendmail $MAILTO

Change the export variables on the top of test.shto reflect your address and filenames.

更改顶部的导出变量test.sh以反映您的地址和文件名。

Download a test pdf document and put it in /home/elcalled pdf-test.pdf

下载一个测试pdf文件并将其放入/home/el名为pdf-test.pdf

Make a file called /home/el/email_body.htm and put this line in it:

创建一个名为 /home/el/email_body.htm 的文件,并在其中添加以下行:

<html><body><b>this is some bold text</b></body></html>

Make sure the pdf file has sufficient 755 permissions.

确保 pdf 文件具有足够的 755 权限。

Run the script ./test.sh

运行脚本 ./test.sh

Check your email inbox, the text should be in HTML format and the pdf file automatically interpreted as a binary file. Take care not to use this function more than say 15 times in a day, even if you send the emails to yourself, spam filters in gmail can blacklist a domain spewing emails without giving you an option to let them through. And you'll find this no longer works, or it only lets through the attachment, or the email doesn't come through at all. If you have to do a lot of testing on this, spread them out over days or you'll be labelled a spammer and this function won't work any more.

检查您的电子邮件收件箱,文本应为 HTML 格式,pdf 文件会自动解释为二进制文件。请注意,一天内使用此功能的次数不要超过 15 次,即使您将电子邮件发送给自己,gmail 中的垃圾邮件过滤器也可以将发送电子邮件的域列入黑名单,而不会让您选择让他们通过。你会发现这不再有效,或者它只允许通过附件,或者根本没有通过电子邮件。如果您必须对此进行大量测试,请将它们分散几天,否则您将被标记为垃圾邮件发送者,此功能将不再起作用。