segunda-feira, 14 de fevereiro de 2011

Envia HTML Mail com Anexo aberto no corpo do e-mail

Sub Initialize

On Error Goto trataerro


Dim session As New notessession
Dim db As notesdatabase
Dim coll As notesdocumentcollection
Dim visao As NotesView
Dim docmail As NotesDocument
Dim docLogo As NotesDocument

Dim rtitem As Variant
Dim filename As Variant
Dim filepath As String
Dim filesname As String
Dim sizeInBytes As Long

Dim notesEmbeddedObject As NotesEmbeddedObject

Set db = session.currentdatabase
'seta o doc p/envio
Set docmail = New NotesDocument(db)


Dim mimeRoot As NotesMimeEntity, mime As NotesMimeEntity
Dim header As NotesMimeHeader
Dim stream As NotesStream
session.ConvertMIME = False ' Do not convert MIME to rich text
Set stream = session.CreateStream()

' Create main MIME message
Set stream = session.CreateStream
Set MIMERoot = docmail.CreateMIMEEntity ' message root

' Create child entities
Set mime = MIMERoot.CreateChildEntity
Set header = MIMERoot.getNthHeader("Content-Type")
Call header.SetHeaderVal("multipart/related")

'seta o path default
filepath = "D:\Diretorio\"

'//seta a visão
Set visao = db.getView("vwLogo")
'//seta o doc. com a imagem a ser anexada no e-mail
Set docLogo = visao.getDocumentByKey("img_LOGO.JPG", True)
'verifica se o documento foi setado corretamente
If docLogo Is Nothing Then
Msgbox "Documento com a imagem não foi encontrado",16,"Operação Cancelada"
Exit Sub
End If

'//seta o nome do anexo
filename = docLogo.ASName(0) ' //ca_labelAnexo

'seta o anexo
Set notesEmbeddedObject = docLogo.GetAttachment( filename )
'verifica se o anexo foi setado corretamente
If notesEmbeddedObject Is Nothing Then
Msgbox "Imagem não encontrada",16,"Operação Cancelada"
Exit Sub
End If
'extrai o anexo
Call notesEmbeddedObject.ExtractFile( filepath & filename )

' Create Message
Call stream.WriteText(|| &_ || & _ |
| & |1. Imagem => | & | | & Oribody & | | & _
|image
| )
Call mime.SetContentFromText(stream,"text/html",ENC_NONE)
Call stream.Close

' Create inline image reference
Set mime = MIMERoot.CreateChildEntity
'Call stream.Open(filepath & filename )

If Not stream.Open(filepath & filename ) Then
Msgbox "Open failed"
Exit Sub
End If
If stream.Bytes = 0 Then
Msgbox "File has no content"
Exit Sub
End If


Call mime.SetContentFromBytes(stream, "image/jpeg",ENC_NONE)
Call stream.Close
Call mime.EncodeContent(ENC_BASE64)
Set header = mime.CreateHeader("Content-ID")
Call header.SetHeaderVal("")

Call docmail.Send(False, "DESTINATARIO")
' Call docmail.Send(false
session.ConvertMIME = True ' Restore conversion


Exit Sub
trataerro:
Msgbox "Error - Linha: " & Cstr(Erl) & " Tipo: "&Cstr(Error) & " " & Cstr(Error)
Exit Sub
End Sub

sexta-feira, 28 de janeiro de 2011

Máscara de campos em Jscript

/**
* Para ser utilizado no evento onKeyPress
* ex:
* CEP -> 99999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* C/C -> 999999-!
* Tel -> (99) 9999-9999
* Hora -> 99:99:99 ou 99:99
* Número -> R$ 99.999,99
*/
function maskField(campo, sMask, event) {

var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
nTecla = event.keyCode;
} else { // Nestcape
nTecla = event.charCode;
}

if(nTecla == 39) return false;

sValue = campo.value;
fldLen = sValue.length;
mskLen = sMask.length;

if (nTecla >= 32) { // Caracteres acima de espaço
if (fldLen < mskLen) { if ((sMask.charAt(fldLen) != "!") && (sMask.charAt(fldLen) != "9")) { sValue = sValue + sMask.charAt(fldLen); campo.value = sValue; if ((nTecla < 48) || (nTecla > 57)) {
return false;
}
} else {
if (sMask.charAt(fldLen) == "9") {
if ((nTecla < 48) || (nTecla > 57)) {
return false;
}
}
}
return true;
} else {
return false;
}
} else { // Caracteres de controle
return true;
}

}







/**
* Use o evento onKeyPress para executar esta função
* ex.:
*
* @param field campo a ser mascarado
* @param maxCharBeforDecimal maximo de caracteres antes da virgula, incluindo os pontos separadores de milhar
* @param event evento do teclado capturado
*
*/
function validateKeyNumber(field, maxCharBeforDecimal, event) {
var valor = field.value
var key;

if(document.all) { // Internet Explorer
key = event.keyCode;
}
else { // Nestcape
key = event.charCode;
}

if (key == 44) {
if (valor == '') {
return false;
}
else if (findVirgula(valor)) {
return false;
}
}
else if (key < 48 || key > 57) {
if (key > 0) {
return false;
}
}

if (valor.length == maxCharBeforDecimal && !findVirgula(valor)) {
if(key != 44 && key != 0) {
return false;
}
}

if (valor.length == 1 && valor.substring(0, 1) == '0') {
if(key != 44 && key != 0) {
return false;
}
}

if (findVirgula(valor)) {
lastCharacter = valor.substring(valor.length - 1, valor.length);

if (lastCharacter != ',') {
index = valor.indexOf(',');
decimal = valor.substring(index + 1, valor.length);

if (decimal.length == 2 && key != 0) {
return false;
}
}
}
return true;
}




/**
* Use o evento onKeyUp para executar esta função
* ex.:
*
* @param field campo a ser mascarado
* @param event evento do teclado capturado
*
*/
function formatMoney(field, event) {
var key;
var valor = field.value;

if(document.all) { // Internet Explorer
key = event.keyCode;
}
else { // Nestcape
key = event.charCode;
}

if (valor.length >= 3 && valor.substring(0, 1) == '0') {
if (valor.substring(1, 2) != ',') {
field.value = valor.substring(1, valor.length)
}
}

if (valor.length > 0 && valor.substring(0, 1) == ',') {
field.value = valor.substring(1, valor.length)
}

if (key != 36 && key != 37 && key != 39 && key != 38 && key != 40 ) {
formatNumber(field)
}

return true;
}

function findVirgula(pDado) {
if(pDado.indexOf(',') > -1) {
return true
}

return false
}

function formatNumber(field) {
dec = ''
arrNum = new Array()
valor = field.value

if (findVirgula(valor)) {
indVirg = valor.indexOf(',')
dec = valor.substring(indVirg, valor.length)
valor = valor.substring(0, indVirg)
}

valor = removePoint(valor)

if (dec != '' && dec.indexOf('.') > -1) {
dec = removePoint(dec)
}

div = valor / 1000

if (div >= 1) {
j = 0

for(i = valor.length; i > 0; i = i - 3) {
if (i - 3 > 0) {
aux = valor.substring(i - 3, i)
arrNum[j++] = '.' + aux
} else {
aux = valor.substring(0, i)
arrNum[j++] = aux
}
}
formattedValue = '';

for(k = j - 1; k >= 0; k--) {
formattedValue += arrNum[k]
}

field.value = formattedValue + dec
}
else {
field.value = valor + dec
}
}

function removePoint(value) {
for(j = 0; j < value.length; j++) { if (value.indexOf('.') > 0) {
j = value.indexOf('.')
aux1 = value.substring(0, j)
aux2 = value.substring(j + 1, value.length)
value = aux1 + aux2
}
}

return value
}

/**
* Use esta função no evento onblur
* ex.:
*
* @param textField campo a ser mascarado
*
*/
function formatDecimal(textField) {
value = textField.value;
indVirg = value.indexOf(',');
isEmpty = value == '';

if (isEmpty) {
return true;
}
if (indVirg == -1) {
value = value + ',00';
textField.value = value;
}
else if (indVirg == value.length - 1) {
value = value + '00';
textField.value = value;
}
else {
decimal = value.substring(indVirg + 1, value.length);

if (decimal.length < 2) { textField.value = value + '0'; } } } /** * Use esta função no evento onblur * ex.:
*
* @param textField campo a ser mascarado
*
*/
function formatDecimal1(textField) {
value = textField.value;
indVirg = value.indexOf(',');
isEmpty = value == '';

if (isEmpty) {
return true;
}
if (indVirg == -1) {
value = value + ',0';
textField.value = value;
}
else if (indVirg == value.length - 1) {
value = value + '0';
textField.value = value;
}
}

sexta-feira, 21 de janeiro de 2011

Gerar PDF a partir de um notesdocument

%REM
Versões anteriores a 7, deve executar o agente com RunOnSeerver
Ambiente nesta solução:
Trab. com um documento SALVO no client Notes e precisava exportar os textos para impressão.
A imagem anexada no cabeçhalho encontra-se em um documento notes que é setado em outra visão.
Para isso foi criado um agente(list Selection / target:none) com o código abaixo:
%END REM


import java.awt.Color;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;

import lotus.domino.Agent;
import lotus.domino.AgentBase;
import lotus.domino.AgentContext;
import lotus.domino.Database;
import lotus.domino.DateTime;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.RichTextItem;
import lotus.domino.Session;
import lotus.domino.Stream;
import lotus.domino.View;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

//import com.lowagie.text.*;
//import com.lowagie.text.pdf.*;


public class JavaAgent extends AgentBase {

public void NotesMain() {

try {

Session session = getSession();
AgentContext agentContext = session.getAgentContext();
Database db = agentContext.getCurrentDatabase();
Agent agent = agentContext.getCurrentAgent();
//System.out.println(agent.getParameterDocID());
Document doc = db.getDocumentByID(agent.getParameterDocID());

String id = doc.getUniversalID();
String filename = id+".pdf";


ByteArrayOutputStream os = new ByteArrayOutputStream(); //( PageSize.A4,esq uerda,direita,topo,rodapé)
com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.A4,35,35,10,35);

PdfWriter.getInstance(document, os);

String strDataTopo = "";

document.open();
document.newPage();


/***************************** MONTANDO O PDF ****************************/

//seta a visão
View visao = db.getView("vwLogo");
// seta o documento com o Logo
lotus.domino.Document docLogo = visao.getDocumentByKey("img_imagem.JPG", true);


//verifica se o documento foi setado corretamente
if (docLogo!=null){

//seta o path do anexo (campo texto)
String filepath = docLogo.getItemValueString("ASName"); //ca_labelAnexo
//seta o nome do anexo
String filesname = filepath.substring(filepath.lastIndexOf("/")+1);
//seta o anexo através do nome
EmbeddedObject file = docLogo.getAttachment(filesname);
//seta o anexo como streaming
InputStream is = file.getInputStream();

//read the inputstream in to a bytearray to pass to PDF image instance
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
bos.write(buf, 0, len);
}
byte[] data = bos.toByteArray();

//seta o logo
Image logo = Image.getInstance(data); /* imagem setada e convertida**/

/*************** *montando o pdf **********/

// seta o campo data p/inserir no cabeçalho

try {
strDataTopo = (new SimpleDateFormat("dd/MM/yyyy")).format(((DateTime)doc.getItemValueDateTimeArray("ca_alert_data").firstElement()).toJavaDate()).toString();
} catch (NotesException e) {
strDataTopo ="";
}


//cria o cabeçalho
float[] widths1 = { 1.25f, 2.25f, 1.75f };

PdfPTable table = new PdfPTable(widths1); // 3 é referente ao número de colunas
PdfPCell c1 = new PdfPCell();
c1.setImage(logo); // <= inseri o logo na primeira coluna
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
c1.setHorizontalAlignment(Element.ALIGN_BOTTOM); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
table.addCell(c1); //inseri a célula na tabela

c1 = new PdfPCell(new Phrase("RESERVADO"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
table.addCell(c1); //inseri a célula na tabela

c1 = new PdfPCell(new Phrase(strDataTopo));
//c1 = new PdfPCell(new Phrase(strDataTopo));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT); //alinhamento Horizontal
c1.setVerticalAlignment(Element.ALIGN_BOTTOM); //alinhamento Vertical
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
table.addCell(c1); //inseri a célula na tabela

// com a tabela com 100% da definição da pagina
table.setWidthPercentage(100);
//adiciona a tabela no document
document.add(table); //inseri a tabela no documento ( pdf )
}
//FIM - cria o cabeçalho


Paragraph myParagraph = new Paragraph( "ALERTA REGIONAL" , new Font(Font.HELVETICA, 10, Font.BOLD));
myParagraph.setAlignment(Element.ALIGN_LEFT);
document.add( myParagraph );
document.add( new Paragraph(" ") );

Paragraph myParagraph2 = new Paragraph( "SEGURANÇA EMPRESARIAL | CONTATO: GDN1" , new Font(Font.HELVETICA, 8, Font.NORMAL));
myParagraph2.setAlignment(Element.ALIGN_RIGHT);
document.add( myParagraph2 );
document.add( new Paragraph(" ") );

Paragraph myParagraph3 = new Paragraph( "Regional: " + doc.getItemValueString("ca_alert_regional") , new Font(Font.HELVETICA, 8, Font.NORMAL));
myParagraph2.setAlignment(Element.ALIGN_LEFT);
document.add( myParagraph3 );
document.add( new Paragraph(" ") );


PdfPTable table2 = new PdfPTable(1); // 3 é referente ao número de colunas
// com a tabela com 100% da definição da pagina
table2.setWidthPercentage(100);
PdfPCell c1 = new PdfPCell();

RichTextItem rti = (RichTextItem)doc.getFirstItem("ca_alert_titulo");
c1.addElement( new Paragraph( new Paragraph( rti.getUnformattedText(),new Font(Font.HELVETICA, 8, Font.NORMAL)))) ;
c1.setBorderColor(new Color(255,255,255)); // Cor da borda da celula
c1.setBackgroundColor(new Color(225,225,225)); // Cor da borda da celula
c1.setHorizontalAlignment(Element.ALIGN_LEFT); //alinhamento Horizontal
table2.addCell(c1); //inseri a célula na tabela
document.add(table2);


RichTextItem rti2 = (RichTextItem)doc.getFirstItem("ca_alert_corpo");
document.add( new Paragraph( rti2.getUnformattedText(),new Font(Font.HELVETICA, 8, Font.NORMAL)) );
document.add( new Paragraph(" ") );


document.close();

/***************************** CRIA O DOCUMENTO TEMPORÁRIO COM O ANEXO ****************************/

Document docTemp = db.createDocument();
docTemp.appendItemValue("Form", "Frm_TempAnexo");
docTemp.appendItemValue("ca_docId_docPai",doc.getUniversalID());
docTemp.appendItemValue("ca_Author",session.getUserName());
docTemp.appendItemValue("ca_excluir","0");
docTemp.save(true,true);


//Put the contents of the text field in to a Notes Stream!
Stream stream=session.createStream();
stream.write( os.toByteArray() );

//Attach file here
if ( !docTemp.isNewNote() )
docTemp.removeItem("Files");

MIMEEntity m = docTemp.createMIMEEntity("Files"); //if no param -- creates a field called Body (so one can't already be on form!)

MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("attachment;filename=\""+filename+"\"");

m.setContentFromBytes(stream, "application/pdf", MIMEEntity.ENC_IDENTITY_BINARY); //ENC_BASE64);
m.decodeContent();


//Following call to doc.save() is NEEDED to commit the MIME to the doc
//even when we're in a WQS doc. Weird?!
//To allow Anonymous users to do so we need to add them to an Authors field (see Form). Even weirder.
docTemp.save(true, true);





} catch(Exception e) {
e.printStackTrace();
}
}
}