How To send email using Adobe AIR? - air

I have searched how to send e-mail using adobe air.. But i didn't find a good one. They only show for adobe flax... There some codes that included some library.
I don't understand how to use it.. Anybody could help?

check out Thibault Imbert's SMTP Mailer. the download (latest version 0.9) includes source files, a library .swc and a sample application for Flash (with frame script).
Update
here's the frame script that is included with the 0.9 release of SMTP Mailer:
import org.bytearray.smtp.mailer.SMTPMailer;
import org.bytearray.smtp.encoding.JPEGEncoder;
import org.bytearray.smtp.encoding.PNGEnc;
import org.bytearray.smtp.events.SMTPEvent;
import flash.utils.ByteArray;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.*;
// create the socket connection to any SMTP socket
// use your ISP SMTP
var myMailer:SMTPMailer = new SMTPMailer (smtp_txt.text, 25);
// register events
// event dispatched when mail is successfully sent
myMailer.addEventListener(SMTPEvent.MAIL_SENT, onMailSent);
// event dispatched when mail could not be sent
myMailer.addEventListener(SMTPEvent.MAIL_ERROR, onMailError);
// event dispatched when SMTPMailer successfully connected to the SMTP server
myMailer.addEventListener(SMTPEvent.CONNECTED, onConnected);
// event dispatched when SMTP server disconnected the client for different reasons
myMailer.addEventListener(SMTPEvent.DISCONNECTED, onDisconnected);
// event dispatched when the client has authenticated successfully
myMailer.addEventListener(SMTPEvent.AUTHENTICATED, onAuthSuccess);
// event dispatched when the client could not authenticate
myMailer.addEventListener(SMTPEvent.BAD_SEQUENCE, onAuthFailed);
// take the snapshot
var myBitmap:BitmapData = new BitmapData ( stage.stageWidth, stage.stageHeight );
// encode as JPEG with quality 100
var myEncoder = new JPEGEncoder( 100 );
send_btn.addEventListener (MouseEvent.CLICK, onClick);
message_txt.text = "<img src='http://www.google.com/images/logo_sm.gif'</img><br><b>Picture file attached ! :)</b>";
function onClick ( pEvt:MouseEvent )
{
// replace this by any DisplayObject
myBitmap.draw ( this );
var myCapStream:ByteArray = myEncoder.encode ( myBitmap );
// sends HTML email
//myMailer.sendHTMLMail ( from_txt.text, to_txt.text, subject_txt.text, "<img src='http://www.google.com/images/logo_sm.gif'</img><br><b>Picture from HTML :)</b>");
// send HTML email with picture file attached
myMailer.sendAttachedMail ( from_txt.text, to_txt.text, subject_txt.text, message_txt.text, myCapStream, "image.jpg");
}
function onAuthFailed ( pEvt:SMTPEvent ):void
{
status_txt.htmlText = "Authentication Error";
}
function onAuthSuccess ( pEvt:SMTPEvent ):void
{
status_txt.htmlText = "Authentication OK !";
}
function onConnected ( pEvt:SMTPEvent ):void
{
status_txt.htmlText = "Connected : \n\n" + pEvt.result.message;
status_txt.htmlText += "Code : \n\n" + pEvt.result.code;
}
function onMailSent ( pEvt:SMTPEvent )
{
// when data available, read it
status_txt.htmlText = "Mail sent :\n\n" + pEvt.result.message;
status_txt.htmlText += "Code : \n\n" + pEvt.result.code;
}
function onMailError ( pEvt:SMTPEvent ):void
{
status_txt.htmlText = "Error :\n\n" + pEvt.result.message;
status_txt.htmlText += "Code : \n\n" + pEvt.result.code;
}
function onDisconnected ( pEvt:SMTPEvent ):void
{
status_txt.htmlText = "User disconnected :\n\n" + pEvt.result.message;
status_txt.htmlText += "Code : \n\n" + pEvt.result.code;
}
function socketErrorHandler ( pEvt:IOErrorEvent )
{
// when data available, read it
status_txt.htmlText = "Connection error !";
}

Related

How to send email and encrypt by google scripts after creating a PDF

I use this code to create pdf files as soon as a client fills the form:
function After_Submit(e){
const info = e.namedValues;
Create_PDF(info);
console.log(info);
}
function Create_PDF(info) {
const PDF_folder = DriveApp.getFolderById("folder id");
const TEMP_Folder = DriveApp.getFolderById("folder id");
const PDF_Template = DriveApp.getFileById("pdf temp id");
const newTempFile = PDF_Template.makeCopy(TEMP_Folder);
const OpenDoc = DocumentApp.openById(newTempFile.getId());
const body = OpenDoc.getBody();
console.log(body);
body.replaceText("{Code}", info['Code'][0]);
body.replaceText("{Date}", info['Date'][0]);
body.replaceText("{Name}", info['Name'][0]);
body.replaceText("{Birthdate}", info['Birthdate'][0])
body.replaceText("{Address}", info['Address'][0]);
OpenDoc.saveAndClose();
const BLOBPDF = newTempFile.getAs(MimeType.PDF);
PDF_folder.createFile(BLOBPDF).setName(info['Name'][0] + " " + info['Code'][0]);
console.log("PDF created");
TEMP_Folder.removeFile(newTempFile);
}
obviously I used also triggers to automate it.
Now the I need to make a function that sends that pdf to the email given on the form by the client, and protects it with his birthdate "for example" as a password!
Can anyone help?
Thank you very much
Unfortunately, Apps Script does not have any specific feature or functionality to set passwords in PDF files, for achieving such a thing you will need to use a third party application, API or library.
To send an email with an attachment you can use the method MailApp.sendEmail as follows (the following piece of code includes self explanatory comments):
function Create_PDF(info) {
const PDF_folder = DriveApp.getFolderById("folder id");
const TEMP_Folder = DriveApp.getFolderById("folder id");
const PDF_Template = DriveApp.getFileById("pdf temp id");
const newTempFile = PDF_Template.makeCopy(TEMP_Folder);
const OpenDoc = DocumentApp.openById(newTempFile.getId());
const body = OpenDoc.getBody();
console.log(body);
body.replaceText("{Code}", info['Code'][0]);
body.replaceText("{Date}", info['Date'][0]);
body.replaceText("{Name}", info['Name'][0]);
body.replaceText("{Birthdate}", info['Birthdate'][0])
body.replaceText("{Address}", info['Address'][0]);
OpenDoc.saveAndClose();
const BLOBPDF = newTempFile.getAs(MimeType.PDF);
///////////////////////// MODIFICATION ////////////////////////////////
// Get the file you want to send as an attachment
var file = PDF_folder.createFile(BLOBPDF).setName(info['Name'][0] + " " + info['Code'][0]);
// Send email using the function sendEmail of MailApp (recipient, subject, message, options)
MailApp.sendEmail('mike#example.com', 'Attachment example', 'PDF attached', {
name: 'Attached file',
attachments: [file.getAs(MimeType.PDF)]
});
/////////////////////////////////////////////////////////////////////////
console.log("PDF created");
TEMP_Folder.removeFile(newTempFile);
}

How to feed a Google Calendar?

I am using this sample to feed my calendar. I have created a Client ID but after I run this project I get 2 errors in console as is shown:
Code:
<html>
<head>
<script type="text/javascript">
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = '633454716537-7npq10974v964a85l2bboc2j08sc649r.apps.googleusercontent.com';
// This quickstart only requires read-only scope, check
// https://developers.google.com/google-apps/calendar/auth if you want to
// request write scope.
var SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load Calendar client library.
authorizeDiv.style.display = 'none';
loadCalendarApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Google Calendar client library. List upcoming events
* once client library is loaded.
*/
function loadCalendarApi() {
gapi.client.load('calendar', 'v3', listUpcomingEvents);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
});
request.execute(function(resp) {
var events = resp.items;
appendPre('Upcoming events:');
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.summary + ' (' + when + ')')
}
} else {
appendPre('No upcoming events found.');
}
});
}
/**
* Append a pre element to the body containing the given message
* as its text node.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to calendar</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<pre id="output"></pre>
</body>
</html>
Console errors:
[Error] Failed to load resource: the server responded with a status of 400 (Bad Request) (auth, line 0)
[Error] Refused to display 'https://accounts.google.com/o/oauth2/auth?client_id=633454716537-7npq10974v964a85l2bboc2j08sc649r.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&immediate=true&include_granted_scopes=true&proxy=oauth2relay396521106&redirect_uri=postmessage&origin=file%3A%2F%2F&response_type=token&state=338793751%7C0.4135151437&authuser=0' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. (about:blank, line 0)
All I want to know is to show the upcoming events from my calendar.
Have anyone any idea how to solve this?
You might try to make sure it is a public calendar.
You can also embed googles calendar in a webpage directly- in calendars/settings
You could also try something like this:
http://mikeclaffey.com/google-calendar-into-html/

Creating Peer Connection for Web RTC Data Channel

I have been trying to establish peer connection between browsers, to use data channel, but i am unsuccessful.
Everytime I correct one statement another error appears.
First I established a socketting server using socket.io and Node.js. In the server when any client is connection I am sending 'beacon' packets. On listening 'beacon' packet 1st client requests to join a 'room'. Then I allow the second client to join the same 'room'.
As soon as the second client connects, Server sends a confirmation packet to Client 1.
Then Client 1 sends the RTC Peer Connection 'offer' to Client 2, after setting local Description.
if( isChrome ) {
localPC = new window.webkitRTCPeerConnection(server, contraints);
rslt.innerHTML = "Webkit Variables Set";
}else {
localPC = new mozRTCPeerConnection(server, contraints);
rslt.innerHTML = "Mozilla Variables Set";
}
localPC.onicecandidate = function(event) {
if( event.candidate )
localPC.addIceCandidate( event.candidate );
};
localPC.onnegotiationneeded = function() {
localPC.createOffer( setOffer, sendFail );
};
sendChannel = localPC.createDataChannel( "sendDataChannel", {reliable: false} );
localPC.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event) {
rslt.innerHTML = event.data;
};
};
localPC.createOffer( setOffer, sendFail );
function setOffer( offer ) {
lDescp = new RTCSessionDescription(offer);
localPC.setLocalDescription( lDescp );
socket.emit( 'offer', JSON.stringify(offer) );
rslt.innerHTML += "Offer Sent...<br/>";//+offer.sdp;
}//End Of setOffer()
Client 2 on receiving the 'offer' sets its as remote Description and creates a 'reply'. Sets the 'reply' as local Description, and sends it.
if( message.type == 'offer' ) {
rDescp = new RTCSessionDescription(message.sdp);
localPC.setRemoteDescription( rDescp );
localPC.createAnswer(
function( answer ) {
lDescp = new RTCSessionDescription(answer);
localPC.setLocalDescription( lDescp );
socket.emit( 'reply', JSON.stringify(answer) );
}, sendFail
);
}else {
localPC.addIceCandidate = new RTCIceCandidate( message.candidate );
}//End Of IF ELse
Client 1 on receiving the 'reply' sets it as remote Description and the connection should get established???
localPC.setRemoteDescription( new RTCSessionDescription( message.sdp ) );
But its not working!!! Pleease Help.
Seems like you got the flow correct, although I don't see the entire code.
One thing that strikes me weird is this:
localPC.onicecandidate = function(event) {
if( event.candidate )
localPC.addIceCandidate( event.candidate );
};
You need to send the icecandidate recieved in the onicecandidate event to the other peer. and not add it yourself.

Cannot view MicrophoneLevel and VolumeEvent session info using OpenTok

I have set up a basic test page for OpenTok using API Key, Session and Token (for publisher). Is based on the QuickStart with code added to track the microphoneLevelChanged event. Page code is available here. The important lines are:
var apiKey = "API KEY HERE";
var sessionId = "SESSION ID HERE";
var token = "TOKEN HERE";
function sessionConnectedHandler(event) {
session.publish(publisher);
subscribeToStreams(event.streams);
}
function subscribeToStreams(streams) {
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
if (stream.connection.connectionId != session.connection.connectionId) {
session.subscribe(stream);
}
}
}
function streamCreatedHandler(event) {
subscribeToStreams(event.streams);
TB.log("test log stream created: " + event);
}
var pubProps = { reportMicLevels: true };
var publisher = TB.initPublisher(apiKey, null, pubProps);
var session = TB.initSession(sessionId);
session.publish(publisher);
session.addEventListener("sessionConnected", sessionConnectedHandler);
session.addEventListener("streamCreated", streamCreatedHandler);
session.addEventListener("microphoneLevelChanged", microphoneLevelChangedHandler);
session.connect(apiKey, token);
function microphoneLevelChangedHandler(event) {
TB.log("The microphone level for stream " + event.streamId + " is: " + event.volume);
}
I know that the logging works, as the logs show up from streamCreatedHandler. However, I am not getting any events logged in the microphoneLevelChangedHandler function. I have tried this with both one and two clients loading the pages (videos show up just fine).
What do I need to do to get the microphoneLevelChanged events to show up?
OpenTok's WebRTC js library does not have a microphoneLevelChanged event so there is nothing you can do, sorry.

Access sd card in android for uploading a file to my php server using phonegap

I want to go to select a file from sdcard and upload it to server. is it possible to access the sdcard in android via phonegap as how we are picking a image from gallery and uploading. I went through samples but all are specifying the file name also like eg: mnt/sdcard/read.txt. But i want to goto only sdcard so that user can select his own file is it possible to do.
U can easily do that its very easy
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccessUpload, fail);
function onFileSystemSuccessUpload(fileSystem) {
// get directory entry through root and access all the folders
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(successReader,fail);
}
function successReader(entries) {
var i;
for (i=0; i<entries.length; i++) {
//alert(entries[i].name);
if(entries[i].isDirectory==true)
{
var directoryReaderIn = entries[i].createReader();
directoryReaderIn.readEntries(successReader,fail);
}
if(entries[i].isFile==true)
{
entries[i].file(uploadFile, fail);
}
}
};
function uploadFile(file) {
var target=""; //the url to upload on server
var ft = new FileTransfer(),path = "file://"+ file.fullPath,name = file.name;
ft.upload(path, target, win, fail, { fileName: name });
// var ft = new FileTransfer();
//ft.upload(file.fullPath, target, win, fail, options);
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
}