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

$ cat mysqldbbackup.sql | mailx backup@email.example

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

虽然这实现了我所需要的,我认为它可以更好的一步,有任何方法,使用shell脚本或其他方式,将压缩的.tar文件作为附件发送到外发电子邮件消息?这将避免处理包含标题数据和经常有换行问题等非常长的电子邮件。


当前回答

如果文件是文本,你可以在正文中最简单地发送它:

sendmail recipient@example.com < message.txt

其他回答

使用mailx命令

 echo "Message Body Here" | mailx -s "Subject Here" -a file_name user@example.com

使用sendmail

#!/bin/ksh

fileToAttach=data.txt

`(echo "To: user@company.example"
  echo "Cc: user@company.example"
  echo "From: Application"
  echo "Subject: your subject"
  echo  your body
  uuencode $fileToAttach $fileToAttach
  )| eval /usr/sbin/sendmail -t `;

对我来说,最近的路是

file=filename_or_filepath;uuencode $file $file|mail -s "optional subject" email_address

举个例子

file=your_sql.log;gzip -c $file;uuencode ${file}.gz ${file}|mail -s "file with magnets" ph.gachoud@gmail.com

好的部分是我可以用Ctrl+r收回它来发送另一个文件…

 echo -e 'Hi, \n These are contents of my mail. \n Thanks' | mailx -s 'This is my email subject' -a /path/to/attachment_file.log -b bcc.email@example.com -c cc.email@example.com -r from.email@example.com to.email1@example.com to.email2@example.com to.email3@example.com

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

mail -s "Backup" -a mysqldbbackup.sql backup@email.example < message.txt

或者:

cat message.txt | mail -s "Backup" -a mysqldbbackup.sql backup@email.example

马鲁蒂尔斯把这事搞得小菜一碟

echo "Body" | mail.mailutils -M -s "My Subject" -A attachment.pdf mail@example.org

-A文件附加一个文件 -M启用MIME,这样您就可以有一个附件和明文正文。

如果尚未安装,请运行

sudo apt install mailutils