Send an Email with Node.JS

In this post, we will be using Node.JS and the nodemailer library to send email. We need to have an email account with an email provider to send email. Gmail or some other email provider should work.

Prerequisites

First lets install some tools

sudo apt install nodejs npm

Now lets install nodemailer

npm install nodemailer

Writing the Code to Send Email

Now that we have nodemailer installed, we can write or copy our code. Create a file called maill.js and make it look similar to the following.

// We can pass in the email text as an argument
const emailText = process.argv.slice(2);
// Or we can just have it as a variable
// const emailText = "NodeJS test email message."
console.log("args " + args)

const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
  host: "mail.emailserver.com",
  port: 465,    //  If your email server does not support TLS, change to 587
  secure: true, // If you are using port 587, change to false.  Upgrade later with STARTTLS
  auth: {
    user: "smtpuser@emailserver.com",
    pass: "notpassword)",
  },
});

const mailOptions = {
  from: 'user@emailserver.com',
  to: "touser@email.com",
  subject: 'Test Email using NodeJS',
  text: `${emailText}`
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Update the following variables

  • host: to your host email server
  • user: to the email user that is sending email. It should have an account on the email server
  • pass: password for your email user that is sending the email
  • from: email address that is sending the email
  • to: email account(s) you are sending email to
  • subject: subject of your email

Now we can proceed to send email

Sending Email

We can now run the code by saving our file and running it directly with NodeJS

nodejs ./mail.js "This is the body text for the email"

Hit Return and look for the email. If something went wrong, it should throw an error.

You can change the emailText variable if you would rather have the message body inside the code.

Code Explanation and Notes

A little explanation on the code.

The second line “const emailText = process.argv.slice(2);” is used to pass in a command line argument to use as the text for the body of the email. You can delete the line and uncomment line 4 if you would rather use a variable inside the code.

Your email server should support using SSL/TLS on port 465. If it does not, you may need to use STARTTLS which uses port 587, and then set secure to false. STARTTLS should upgrade the connection to be encrypted. But it’s opportunistic. You can read more about STARTTLS, SSL/TLS here https://mailtrap.io/blog/starttls-ssl-tls/

You can change the “to: ” in the mailOptions object to an array of email addresses to send the email to multiple people at once.

to: ["email1@email.com", "email2@email.com", "etc"],

Simple JavaScript Object – Code Example

Below is a code example for creating a basic object and using a function to calculate the fuel economy.

// New object Car
const car = {
    make: 'Honda',
    model: 'Civic',
    topSpeed: 100,
    tankCapacity: 10,
    range: 300,
    MPG: function() {
        this.mpg = this.range / this.tankCapacity;
        return this.mpg
    }
}

car.MPG();  // We need to call this to calculate the MPG, otherwise we get undefined

console.log(`My car is a ${car.make + " " + car.model }, can go ${car.topSpeed}/MPH, and gets ${car.mpg}/MPG `)

// Alternatively we can call the function car.MPG() directly.  
// This keeps us from having to run the function before logging.
console.log(`My car is a ${car.make + " " + car.model }, can go ${car.topSpeed}/MPH, and gets ${car.MPG()}/MPG `)

How to Find Yesterdays Date in Linux

The wrong way to find yesterdays date:

I had a command that was used to see if. It used some arithmetic operators to subtract 1 from the current day. That would give us yesterdays day which we could then use to check if a backup was created then.

day=$(date +%d) ; date=$(($day - 1)) ; echo "yesterday date is $date"

It worked great, unless you happened to be on the 8th or 9th of the month. Looks like bash is interpreting 08 and 09 in octal format. https://stackoverflow.com/questions/24777597/value-too-great-for-base-error-token-is-08

-bash: 08: value too great for base (error token is "08")

The better way

Fortunately there is an easier and more reliable way to do this. Using the date command, you can specify yesterday and it will print out yesterdays date.

date --date=yesterday +%d

Much easier to use.

Some more info.

https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html?cf_chl_captcha_tk=N9iBfod_b0qUxjB2jIGlETgiZ.JXSxGpLmvQ83CzBvY-1636407896-0-gaNycGzNBmU

https://stackoverflow.com/questions/18180581/subtract-days-from-a-date-in-bash

Unity – Rotate Player by Dragging Finger on Screen

C# Code for rotating a player in Unity by swiping on the screen.

This is actually really simple to do. Create a script called PlayerRotation or something, then put in the following code.

 
 public float speed;
 void Update()
    {
        // Touch controls for rotation
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
            // Rotate Player.  Could change Rotate to Translate to move the player.
            transform.Rotate(0, touchDeltaPosition.x * speed, 0);
   

    }

Assign the Script to the player and specify the speed in the Unity Inspector. The public float speed variable will increase or decrease how fast you rotate around. You can also set it to a negative number to rotate the opposite direction you drag with your finger.

Unity speed of rotation for player.

Android Button – Remove Shadow and Border from Button with Image on it

We can remove the border and shadows from a button by adding the following style code in your activity_main.xml file. Or what ever your XML file is.

style="?android:attr/borderlessButtonStyle"

Code for button. We are setting an image as the background.

  <Button
        android:id="@+id/button"
        style="?android:attr/borderlessButtonStyle"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:background="@drawable/gear"
        android:onClick="launchSettings"
        android:textSize="12sp"/>

Comparison of buttons. One on the left still has the shadow on it

Difference between border and borderless buttons

More info here

https://stackoverflow.com/questions/28756035/how-to-remove-button-shadow-android
https://stackoverflow.com/questions/27867284/remove-shadow-effect-on-android-button/30856094

Getting Android WiFi state in Kotlin

In Kotlin you can request if the WiFi adapter is on or off with the following code
This changes the text on a textbox, replace with your textbox.

wifiManager = this.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
textBox.text = "WiFi State = ${wifiManager.wifiState}"

The important part is

wifiManager.wifiState

It will return a number from 0-4 which indicates if it is on or off.

0 = WiFi is being disabled
1 = WiFi Disabled
2 = WiFi is being enabled
3 = WiFi is Enabled
4 = Error

https://developer.android.com/reference/kotlin/android/net/wifi/WifiManager#WIFI_STATE_DISABLED:kotlin.Int

Kotlin, Launching Settings Activity is Showing Main Activity

The problem is that the code in SettingsActivity is not tied to the settings_activity.xml file. So it is using the activity_main.xml instead. It does in fact switch activities, the header at the top shows that it is in the Settings, but it shows the same information on the Main Activity. Problem showed up after copying and pasting code.

Check the following line under the initial onCreate function

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)  // <-- Should be R.layout.settings_activity

The setContentView line should reflect the Layout XML file under res -> layout -> settings_activity.xml

You need to use a Theme.AppCompat theme (or descendant) with this activity.

https://stackoverflow.com/questions/21814825/you-need-to-use-a-theme-appcompat-theme-or-descendant-with-this-activity

You need to use a Theme.AppCompat theme (or descendant) with this activity.

Looks like you can get the above error resolved by adding the following to the Android Manifest file.

android:theme="@style/Theme.AppCompat.Light

Kotlin – Buttons and TextViews

Set Text for text view

val textBoxVar: TextView = findViewById(R.id.textBoxID)
textBoxVar.text = "Hello World!"

Button clicked – do something

val buttonVar: Button = findViewById(R.id.buttonID)
buttonVar.setOnClickListener {
    buttonVar.text = "Button Pushed..."  //Change text on button

}

Toast notification

val text = "Hello World! This is a toast message!"
val duration = Toast.LENGTH_SHORT
val toast = Toast.makeText(applicationContext, text, duration)
toast.show()