Send Mail via Java

I recently needed to send an email via Java. This was the first time i tried to do this, so I’ll post the code here. Maybe someone can use this one day.

First of all, you need to get JavaMail library here: http://www.oracle.com/technetwork/java/javamail/index-138643.html

Then you can create a class called “Mail” or “MailService”. Then paste the following code:

import java.util.Properties;
 import javax.mail.Authenticator;
 import javax.mail.Message;
 import javax.mail.MessagingException;
 import javax.mail.PasswordAuthentication;
 import javax.mail.Session;
 import javax.mail.Transport;
 import javax.mail.internet.AddressException;
 import javax.mail.internet.InternetAddress;
 import javax.mail.internet.MimeMessage;

public class Mail {
 private static final String EMAIL = "user@gmail.com";
 private static final String PASSWORD = "supersecretpassword";
 private static final String USERNAME = "totallysillyusername";
 private static final int SMTP_PORT = 25;
 private static final String SMTP_HOST = oldschoolemailhost.com";

public static void send(String recipient, String subject, String text) throws AddressException, MessagingException {
 Properties properties = System.getProperties();
 properties.setProperty("mail.smtp.host", SMTP_HOST);
 properties.setProperty("mail.smtp.port", String.valueOf(SMTP_PORT));
 properties.setProperty("mail.smtp.auth", "true");
 Session session = Session.getDefaultInstance(properties, new MailAuthenticator(USERNAME, PASSWORD));
 MimeMessage msg = new MimeMessage(session);
 msg.setFrom(new InternetAddress(EMAIL));
 msg.setRecipients(Message.RecipientType.TO,
 InternetAddress.parse(recipient, false));
 msg.setSubject(subject);
 msg.setText(text);
 Transport.send(msg);
}
}

class MailAuthenticator extends Authenticator {
 private final String user;
 private final String password;

public MailAuthenticator(String user, String password) {
 this.user = user;
 this.password = password;
 }

@Override
 public PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication(user, password);
 }
 }

Something special about this code is the MailAuthenticator. You normally don’t write an extra class for this, but it makes the code more readable I think.

Then you can call this class everywhere like that:

String recipient = "bobama@me.com";
String subject = "topic";
String text = "smile =)";

Mail.send(recipient, subject, text);

And thats it, it’s really easier then I expected. Try it out =).

Eclipse doesn’t highlight references anymore

I had this problem this morning. My eclipse wasn’t highlighting references anymore. The fix for this problem is quite easy. Just go to Window -> Preferences -> Java -> Editor -> Mark Occurrences an activate it there:

Screen Shot 2013-03-02 at 08.04.34

Dart: functions

I wanted to give you some short snippets about functions in dart. They can really help you. The first thing is how you can write a method in one line:

sayHello() => "Hello";

This is helpful for dummy stuff and so on. But now something more special. This parameters in square brackets is known as optional positional parameter. An example:

String saySomething(String thingToSay, [String name]){
 if(name != null){
 return "$thingToSay $name";
 } else {
 return thingToSay;
 }
 }

You then can call this method in 2 ways.

  1. print(saySomething(“I really like pasta”));
  2. print(saySomething(“I really like”, “Dart”));

But when you want to write more readable code, then try the optional named parameter.  For this you can use curly brackets. You can give a default value too. An example:

screamAndShout(String scream, {int times: 1}){
 for(int i = 0; i<times;i++){
 print(scream.toUpperCase());
 }
 }

The usage looks like this:

  1. screamAndShout(“i love dart”, times : 4);
  2. screamAndShout(“i love dart”);

I think all of this things can really help.

Dart: Math Constants

Another small feature of the dart math library are math constants. Just import the following line:

import 'dart:math' as math;

This are all the math constants the library knows:

E (Base of the natural logarithms)

print(math.E);

Result: 2.718281828459045

PI

print(math.PI);

Result: 3.141592653589793

SQRT2 (Square root of 2)

print(math.SQRT2);

Result: 1.4142135623730951

LN10 (Natural logarithm of 10)

print(math.LN10);

Result: 2.302585092994046

LN2 (Natural logarithm of 2)

print(math.LN2);

Result: 0.6931471805599453

LOG10E (Base -10 logarithm of [E])

print(math.LOG10E);

Result: 0.4342944819032518

LOG2E (Base -2 logarithm of [E])

print(math.LOG2E);

Result: 1.4426950408889634

SQRT1_2 (Square root of 0.5)

print(math.SQRT1_2);

Result: 0.7071067811865476

Dart: Trigonometry

Here are some examples for this topic.

import 'dart:math' as math;

void main() {
var beta = 40;
var radians = beta * (math.PI / 180);
print("beta = $beta°: $radians");

var sinBeta = double.parse(math.sin(radians).toStringAsPrecision(3));
var cosBeta = double.parse(math.cos(radians).toStringAsPrecision(3));
var tanBeta = double.parse(math.tan(radians).toStringAsPrecision(3));

print("sinus : $sinBeta");
print("cosinus : $cosBeta");
print("tangens : $tanBeta");
}

Its very simple, and there is something real cool about Dart that we see here:

toStringAsPrecision(3)

This automatically rounds the number up or down. So the number -1.117214930923896 gets -1.12. I think this really makes many things easier when you work with this kind of math things. Another nice thing that you can see here is the following print-method:

print("beta = $beta°");

No need to use tokens like ‘+’ or ‘.’. Just use ‘$’. By the way, the output looked like that:

beta = 40°: 0.6981317007977318
sinus : 0.643
cosinus : 0.766
tangens : 0.839

Google ‘maps’ the Grand Canyon

Just search for it at Google Maps =).

Screen Shot 2013-02-07 at 21.21.31

The official announcement of Google.

Dart: sqljocky example

This time we want to get the data from the database directly. We will use the sqljocky package to do this. First of all we create a new console dart application. After that we need to get the package from the pub.

  1. Create a pubspec.yaml file in the project and add the following text:
     name: my_app
     dependencies:
      web_ui: any
  2. Rightclick on the pubspec.yaml file and choose Tools > Pub Install.
    Screen Shot 2013-01-27 at 12.44.10
  3. Now you can see a new package in the packages folder:
    Screen Shot 2013-01-27 at 12.50.26

In the .dart file we now need to add the import to the package:

import 'package:sqljocky/sqljocky.dart';

Now we can access this package. The following code is doing the whole action:

void main() {
 var con = new ConnectionPool(host: 'localhost', port: 3306, user: 'root', password: null, db: 'mymusic', max: 5);
 con.query('select albumName, interpret from cd').then((result)
 {
  var row;
  for (row in result) {
  print('album: ${row[0]} (${row[1]})');
 }
}
);
}

The code is real simple. The library is really doing a lot for us. To read from the result of the select-statement we can use a simple foreach snippet:

var row;
for (row in result) {
 print('album: ${row[0]} (${row[1]})');
}

The output in the console looks like that:

Screen Shot 2013-01-27 at 13.10.04

This are the things I really love about dart. Just a few easy lines of code for a great result.

Android CardsUILib

I recently searched for a Google Now Card library and I found CardsUILib. But I wanted a card with a picture, so I can use it in my quiz app. So I edited the whole library a bit and the result is that:

It’s a great library with a lot of potential. I did a pull request for a picture card. You can find the library here: https://github.com/nadavfima/cardsui-for-android/tree/master/CardsUILib

The edit was real easy, I created a new XML-File:

...

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selectable_background_cardbank"
android:gravity="center_vertical"
android:padding="8dp" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="154dp"
android:layout_height="127dp"
android:adjustViewBounds="true"
android:baselineAlignBottom="true"
android:scaleType="centerCrop"
android:src="@drawable/url1" />

<TextView
android:id="@+id/description"
style="@style/CardText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:ellipsize="end"
android:maxLines="7"
android:text="text text" />

...

And the Java class looked like that:


public class MyImageCard extends Card {

public MyImageCard(String title, int image){
 super(title, image);
}

@Override
public View getCardContent(Context context) {
 View view = LayoutInflater.from(context).inflate(R.layout.card_picture, null);
 ((TextView) view.findViewById(R.id.title)).setText(title);
 ((ImageView) view.findViewById(R.id.imageView1)).setImageResource(image);

return view;
}
}

As you see, the changes I made were real simple as you saw. But there were more in the library code. There I just added an Integer for the DrawableRessource.

Dart: Parse JSON to object

As we saw in the first post: http://www.signer.pro/lets-meet-dart/ its real easy to work with Dart. We want to parse the JSON-Objects, that you can get here(http://api.signer.pro/client.php?action=getCds) to Dart-Objects. First of all we will write a normal console application and after that a web application where we display the data a bit nicer.

Dart Console Application

First of all we create a cd-class with all the information we need:

class Cd {
  num id;
  String album;
  String interpret;

 Cd(num id, String album, String interpret){
  this.id = id;
  this.album = album;
  this.interpret = interpret;
 }

 Cd.fromJson(Map json){
  id = json['id'];
  album= json['album'];
  interpret = json['interpret'];
 }
}

Some of the relevant data types in our example are num and String. There is also bool, but we don’t need that one in the example.

So after we wrote the Dart-Object, let’s work with the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
var httpClient = new HttpClient();
var conn = httpClient.getUrl(new Uri('http://api.signer.pro/client.php?action=getCds'));
conn.onResponse = (HttpClientResponse resp) {
var input = resp.inputStream;
input.onData = () {
var data = input.read();
var text = new String.fromCharCodes(data);
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
listOfCds.forEach((cd) {
print("album = ${cd.album} interpret = ${cd.interpret}");
});
};
input.onClosed = () => httpClient.shutdown();
};
}

We created a httpClient with the URL to the API. Then we get the response and get the text with the following command:

var text = new String.fromCharCodes(data);

Then we parse the JSON-text into a List. Because we’ve got a JSON-Array with some JSON-Objects. And now something that I love the most of the Dart-Language:

l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});

This way, we can simply loop through a list and do something with the objects. In this case we map the value with the key ‘id’ or ‘album’ and create a Cd-Object with it. After that we add it to a list of Cd’s we defined earlier.

pp1

So, as wee see this is working pretty well. And now we do almost the some for a small web application.

Dart Web Application

As in the console application we define a CD-Object. After that we use the following code in the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
ParagraphElement p = new ParagraphElement();
p.text = "loading..";
query("#container").append(p);
var request = new HttpRequest.get('http://api.signer.pro/client.php?action=getCds', (req) {
var text = req.responseText;
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
UListElement ule = new UListElement();
listOfCds.forEach((cd) {
LIElement lie = new LIElement();
lie.text = "${cd.album} (${cd.interpret})";
ule.children.add(lie);
});
p.remove();
query("#container").append(ule);
});
}

We needed to modify the code a bit, so it matches the the  ‘dart:html’ library. But the rest of the code is very similar to the code in the first example above. The HTML looks like that:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ConnectAPI</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet"></link>
</head>
<body>
<h1>ConnectAPI</h1>
<div class="span12" id="container">
</div>
<script type="application/dart" src="ConnectAPI.dart"></script>
<script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
</body>
</html>

As you see, I’m using bootstrap again for the website. So the result in the browser looks like that:

pp2

Let’s meet Dart

dart

It’s a long time ago, I first heard something about Dart. It’s the Google answer for JavaScript. You can download it over here: http://www.dartlang.org/downloads.html

When you create a new project you’ll get a .css, .dart and a .html file. We want to do a simple counter, so when you click on it, this value will increase.

We start with the HTML-File. This contains a basic website structure. I would use bootstrap for early development, but at the moment we don’t need it.

<!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">
 <title>HelloWorld</title>
 <link rel="stylesheet" href="HelloWorld.css">
 </head>
 <body>
 <h1>HelloWorld</h1>
 <p>Hello world from Dart!</p>
 <script type="application/dart" src="HelloWorld.dart"></script>
 <script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
 </body>
 </html>

New we add a new add a new parameter tag with a uniq id below the “Hello world from Dart”-thing.

<p id="counter"></p>

The next step is the CSS-File so we can fully concentrate about dart-source-code  later. Remove everything except the body and p part and then add the following one for the counter:[/html]

#counter {
 font-size: 24pt;
 text-align: center;
 margin-top: 140px;
 }

Now we can go to the .dart-File. You can remove almost everything, but keep the

import 'dart:html';
void main() {
}

We start with the following code:

void main() {
 query("#counter")
 ..text = "0"
 ..on.click.add(countOneUp);
 }

This is simply setting the text of our HTML-element, with the id ‘counter’, and adding an OnClickEvent. This is very similar to Java, not the syntax, but the structure how you work with it. So now we need to create the OnClickEvent.

void countOneUp(Event event) {
 var tempCount = query("#counter").text;
 int i = int.parse(tempCount);
 i++;
 query("#counter").text = i.toString();
 }

If you know how Java-Syntax is working, this code isn’t hard to understand. But I think the query-command is quite confusing if you us it the first few times. As you see, I did a lot of filetype-parsing.

To run the application simply hit Ctrl + R (I don’t know how this is on Mac ^^). A modified version of chromium is now starting and will run the application. It should look like this now:

You can find the examples here: http://dart.signer.pro/.

As you see, Dart can be pretty nice. But I haven’t done much more at the moment. If I know more, I’ll let you know.