here is the code i use on a custom program to add an image to a post, you need the post id. you can get that when you run "wp_insert_attachment" , it returns the id.
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
if it's the first/only image attachment, it will get used as the thumbnail. if not you can assign it as one with:
add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
though, you need to make sure it is the right size. if it's too big it will only show part of it as the thumbnail. for that, i implemented a php image resize function, which is common, google.