Bash Script that sends email from bash to someone....

Step:1
Install ssmtp

Step:2
configure ssmtp
/etc/ssmtp/ssmtp.conf

root=testin.mav@gmail.com
mailhub=smtp.gmail.com:587
AuthUser=testin.mav@gmail.com
AuthPass=HENRY
UseTLS=YES
UseSTARTTLS=YES
AuthMethod=LOGIN
FromLineOverride=YES

Step:3 Script
#!/bin/bash

# Email details
TO_ADDRESS="akshaw@aol.com"
FROM_ADDRESS="testin.mav@gmail.com"
SUBJECT="Test email from Bash script"
BODY="This is a test email sent from a Bash script using ssmtp."

# Create the email content
EMAIL_CONTENT="To: ${TO_ADDRESS}
From: ${FROM_ADDRESS}
Subject: ${SUBJECT}

${BODY}"

# Send the email
echo "${EMAIL_CONTENT}" | ssmtp ${TO_ADDRESS}

Step:4
./Email_Scripts.sh

From here related authentication

Storing passwords in plaintext in scripts or configuration files is insecure because it exposes sensitive information to potential unauthorized access. Instead, consider using more secure methods such as environment variables, secure vaults, or OAuth2 for authentication. Here's a detailed explanation of each method:

### 1. Environment Variables
Environment variables can be used to store sensitive information, including passwords, without hardcoding them into scripts. This method is more secure as it separates configuration data from the code.

#### Example:

**Step 1:** Set environment variables in your shell or in a configuration file:

```bash
export EMAIL_USER="testin.mav@gmail.com"
export EMAIL_PASS="YOUR_APP_PASSWORD"
```

**Step 2:** Modify your Bash script to use these variables:


```bash
#!/bin/bash

# Define email parameters
TO_ADDRESS="akshaw@aol.com"
FROM_ADDRESS="$EMAIL_USER"
SUBJECT="Test email from Bash script"
BODY="This is a test email sent from a Bash script using ssmtp."

# Create the email content
EMAIL_CONTENT="To: ${TO_ADDRESS}
From: ${FROM_ADDRESS}
Subject: ${SUBJECT}

${BODY}"

# Send the email using ssmtp
echo "${EMAIL_CONTENT}" | ssmtp ${TO_ADDRESS}
```

### 2. Secure Vaults
Secure vaults like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault can securely store and manage sensitive information. These services provide controlled access to secrets and often integrate with various authentication methods.

#### Example with HashiCorp Vault:

**Step 1:** Store the secret in Vault:

```bash
vault kv put secret/email_credentials email_user="testin.mav@gmail.com" email_pass="YOUR_APP_PASSWORD"
```

**Step 2:** Modify your script to retrieve the secret from Vault:

```bash
#!/bin/bash

# Retrieve secrets from Vault
EMAIL_USER=$(vault kv get -field=email_user secret/email_credentials)
EMAIL_PASS=$(vault kv get -field=email_pass secret/email_credentials)

# Define email parameters
TO_ADDRESS="akshaw@aol.com"
FROM_ADDRESS="$EMAIL_USER"
SUBJECT="Test email from Bash script"
BODY="This is a test email sent from a Bash script using ssmtp."

# Create the email content
EMAIL_CONTENT="To: ${TO_ADDRESS}
From: ${FROM_ADDRESS}
Subject: ${SUBJECT}

${BODY}"

# Send the email using ssmtp
echo "${EMAIL_CONTENT}" | ssmtp ${TO_ADDRESS}
```

### 3. OAuth2 for Gmail
OAuth2 is a more secure authentication method for accessing Gmail, as it avoids using passwords and instead uses tokens. Python's `smtplib` can be configured to use OAuth2 tokens.

#### Example with Python and OAuth2:

**Step 1:** Install required libraries:

```bash
pip install google-auth google-auth-oauthlib google-auth-httplib2
```

**Step 2:** Set up OAuth2 credentials in Google Cloud Console and download the `credentials.json` file.


**Step 3:** Use the following Python script to send an email using OAuth2:

```python
import os
import base64
import smtplib
import google.auth
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Load OAuth2 credentials
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
creds = Credentials.from_authorized_user_file('credentials.json', SCOPES)
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        raise Exception("Invalid or missing credentials")

def send_email(message, from_addr, to_addr):
    # Create the email message
    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = 'Test email from Python using OAuth2'
    msg.attach(MIMEText(message, 'plain'))

    # Connect to the Gmail SMTP server using OAuth2
    encoded_creds = base64.urlsafe_b64encode(creds.to_json().encode('utf-8')).decode('utf-8')
    smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
    smtp_server.starttls()
    smtp_server.ehlo()
    smtp_server.auth('XOAUTH2', lambda: 'user=%s\1auth=Bearer %s\1\1' % (from_addr, creds.token))
    smtp_server.sendmail(from_addr, to_addr, msg.as_string())
    smtp_server.quit()

# Send the email
send_email("This is a test email sent using OAuth2", "testin.mav@gmail.com", "akshaw@aol.com")
```

### Summary
- **Environment Variables:** Secure and separate configuration data from code.
- **Secure Vaults:** Use dedicated secret management services for better security and access control.
- **OAuth2 for Gmail:** Avoid using passwords and use tokens for authentication, providing a more secure and modern approach.

Each method improves security by reducing the risk of exposing sensitive credentials.

Comments

Popular posts from this blog

SAMBA SERVER 2.0 #server

From cool things #1 Hosting a website on apache ubuntu server and you can host directory and files to just remove index. html