在平时使用树莓派的过程中,大多数人的习惯都是直接使用终端去连接树莓派,很少使用屏幕去直接操作;而在连接终端的时候又必须要知道树莓派的IP地址;这时候如果树莓派能够通过邮件的方式直接将自己的IP地址直接发送给我们,在连接时就会省去很多不必要的麻烦。

安装软件

  • 安装mutt:$sudo apt-get install mutt
  • 安装msmtp:$sudo apt-get install msmtp

设置软件

  • 设置mutt

    编辑/etc/Muttrc 系统全局设置

    编辑~/.muttrc 为某个系统用户设置

    这里对全局进行设置

    $sudo vim /etc/Muttrc

    在文件最后面添加如下代码

    set sendmail="/usr/bin/msmtp"
    set use_from=yes
    set realname="Raspberry"          #邮箱发送人昵称
    set from=xxxxx@xxx.com    #自己的发件箱邮箱地址
    set envelope_from=yes
    set crypt_use_gpgme=no
  • 登录邮箱,进入邮箱设置界面,开启邮箱的IMAP/SMTP服务

    下图为163邮箱

    NHVGLK3YN1G68YJBOYT

设置msmtp

  • 创建 ~/.msmtprc 和 ~/.msmtp.log 两个文件分别作为msmtp的配置文件和日志文件

    编辑.msmtprc

    vim ~/.msmtprc

    account default   
    host smtp.163.com   #自己邮箱的smtp地址,我的是163邮箱,所以是这个
    from mstz1130@163.com    #自己的邮箱地址
    auth plain
    user mstz1130        #自己的邮箱用户名,就是@前的
    password xxxxxxxx   #这个并不是邮箱密码,是邮箱授权码
    logfile ~/.msmtp.log
            #日志文件地址

    由于password是明码,所以我们要修改文件的权限

    $sudo chmod 600 .msmtprc

    163邮箱授权码的开启位置,其他邮箱的具体位置请自行查询。

    2FUYGZLJWT4DM@RES

测试邮件发送

$ echo "正文" | mutt -s ”主题“ xxx@xx.com -q 附件

获取IP地址脚本

可以在任意可执行位置创建

$vim sendip.sh

#!/bin/bash

# check network availability

SITE_TO_CHECK="www.163.com"
while true
do
    TIMEOUT=5
    RET_CODE=`ping -s 1 -c 1 $SITE_TO_CHECK`
    if [ "$?" != "0" ]
       then
        echo "Network not ready, wait..."
        sleep 1s 
    else
        echo "Network OK, will send mail..."
        break
    fi
done

# get the IP address of eth0, e.g. "192.168.x.x"
WLAN0_IP_ADDR=`ifconfig wlan0 | sed -n "2,2p" | awk '{print substr($2,1)}'`
ETH0_IP_ADDR=`ifconfig eth0 | sed -n "2,2p" | awk '{print substr($2,1)}'`
ETH1_IP_ADDR=`ifconfig eth1 | sed -n "2,2p" | awk '{print substr($2,1)}'`
ETH2_IP_ADDR=`ifconfig eth2 | sed -n "2,2p" | awk '{print substr($2,1)}'`

# send the Email
echo "Current time: `date '+%F %T'`
WLAN0 IP Address of Raspberry Pi: $WLAN0_IP_ADDR
ETH0 IP Address of Raspberry Pi: $ETH0_IP_ADDR
IP address loading completed ! ! !" | mutt -s "IP Address of Raspberry Pi" xxx@xxx.com

写入开机启动项

$sudo vim /etc/rc.local

在exit 0之前加入以下命令

su pi -c /home/pi/sh/sentIP.sh &

具体路径由自己创建的脚本地址位置来决定,&表示并发执行,在脚本运行时不影响其他脚本

最后修改:2024 年 05 月 12 日
如果觉得我的文章对你有用,请随意赞赏