Facebook

How to send email using python

To send the mail to multiple people using code is easy. Copy paste the below line in a text file and save as mail.py.  Replase the me@gmail.com with your actual email address and you@gmail.com with the address to whom you want to send the email.

Make sure your access level settings in gmail account are set to low.
go to this link https://www.google.com/settings/u/1/security/lesssecureapps
and check radio button 'Turn on'.

# code starts here ...

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "me@gmail.com"
you = "you@gmail.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
Your html content goes here...
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# image attachment code here

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('username', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

# code ends here ...


You can also attach file/images to your email.  Use the below code snippet for same.

#attaching an image as attachment. START

ImgFileName = '/home/rana/Pictures/1.jpg'
img_data = open(ImgFileName, 'rb')
image = MIMEApplication(img_data.read(), Content_Disposition='attachment; filename="%s"' % basename(ImgFileName), Name=basename(ImgFileName))
msg.attach(image)

#attaching an image as attachment. END

You can use for loop to send the same mail to multiple people. That part I leave up to you.


If you face any issue while sending mail using this code, let me know.






Finding file and directory in ubuntu


To find a file in your system by name use below command -

find -name "query"

For case insensitive search -
find -iname "query"

Create a bootable Pen Drive in Ubuntu


Ubuntu have a default program to create a bootable pen drive.
Follow these steps to create the same.

1. Download the iso image file of latest Ubuntu from their official site.
2. Now attach an empty USB drive to the system.
3. Start the 'startup disk creator' program.


4. Select the downloaded iso image file as the source file.


5. Select the USB device as the 'disk to use'.
6. Select less than 1 GB Reserved disk space. Click 'Make Startup Disk'.


7. Files will be copied to disk. After some time when OS installation on the disk is complete click the 'quit' button.



8. Detach the USB disk and follow this article to install the Ubuntu on any system. 

Leave a comment in case of any query.

Classic snake game in Linux terminal

Hello Friends,

You must have played the classic snake game on feature phones like Nokia 1100.
Now you can again play the same game in Linux terminal.
For this you need to install nsnake package by running below command in terminal.


sudo apt-get install nsnake


After the package is installed , run the game by running nsnake command.




Use the up and down arrow keys to change to game mode to Borders On and Borders Off.
Use left and right arrow keys to change the speed.
Press enter or space to start the game one you are done with settings.
You can exit the game by pressing q key.




Rules are the same as they were in classic game.
If you collide with yourself (snake), you die. Game over.




Download the latest version of this game from Github.
Buy cheapest nokia mobile phones here.


Transferring data between two activities

In the last article we saw how to create an activity with text fields , access the data from those text fields and then display that text.

Creating an activity with text fields

If you are learning android from starting and haven't read the first article then I recommend to do so.

Start developing android applications.

To transfer data from one activity to another we need to create another activity. Let's name this activity as DisplayActivity.

To display the transferred text on this activity, create a textview. Set the font size, font color and other parameters.


activity_display.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="mycompany.helloworld.DisplayActivity">

    <TextView
        android:id="@+id/displaymsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:textColor="@android:color/holo_blue_light"
        android:layout_margin="20dp"
        android:layout_centerInParent="true"/>

</RelativeLayout>



TextView will display the text passed to this activity with text size as 20dp and in holo blue color. Margin will leave the 20dp of empty space around the textview.
layout_centerInParent will align the textview in center, vertically and horizontally both.


We will use the MainActivity created in previous article to enter the data. For this article we will modify the code a little bit. Instead of displaying the data, we will start another activity.
MainActivity.xml (modified)


<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView android:text="@string/signin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textColor="@android:color/background_dark"
            android:gravity="center"
            android:padding="10dp"/>

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:hint="Email"
            android:inputType="textEmailAddress"/>

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:hint="Password"
            android:inputType="textWebPassword"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/login"
            android:background="@android:color/holo_blue_dark"
            android:onClick="startAnotherActivity"
            android:layout_margin="10dp"/>



    </LinearLayout>
</RelativeLayout>


Now on click of login button, we will call the function startAnotherActivity.

MainActivity.java (modified)


package mycompany.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void startAnotherActivity(View view) {
        String email = getEmail();
        String password = getPassword();
        Intent intent = new Intent( this, DisplayActivity.class);
        intent.putExtra("email", email);
        intent.putExtra("pass",password);
        startActivity(intent);
    }

    public String getEmail() {
        EditText editText = (EditText)findViewById(R.id.email);
        String email = editText.getText().toString();
        return email;
    }

    public String getPassword() {
        EditText editText = (EditText)findViewById(R.id.password);
        String password = editText.getText().toString();
        return password;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Now in DisplayActivity we will collect the data and display it.

DisplayActivity.java


package mycompany.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import org.w3c.dom.Text;

public class DisplayActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Intent intent = getIntent();
        String email = intent.getStringExtra("email");
        String password = intent.getStringExtra("pass");
        TextView tv = (TextView) findViewById(R.id.displaymsg);
        tv.setText("Email : "+email+"\nPassword : "+password);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

You can also use the captured data for validation purpose. Store the actual email and password in a constants file and match them with entered value. If successful then proceed else redirect them to login screen.

Run the code and comment about your findings.