How to change "to-reply" property of email in alfresco - alfresco

I am able to send emails in alfresco using Java API but I am not able to change the "Reply-to: " property like this in alfresco :
Message replyMessage = new MimeMessage(session);
replyMessage = (MimeMessage) message.reply(false);
replyMessage.setFrom(new InternetAddress(to));
replyMessage.setText("Thanks");
replyMessage.setReplyTo(message.getReplyTo());
replyMessage.setReplyTo(message.getReplyTo());
This is my code to send emails
NodeRef companyHome = repository.getCompanyHome();
List<String> pathElements = new ArrayList<>();
pathElements.add("Data Dictionary");
pathElements.add("Email Templates");
pathElements.add("Trams Email Templates");
pathElements.add("CONTENT_NOTIFICATION.html.ftl");
FileInfo templateFile;
try {
templateFile = serviceRegistry.getFileFolderService()
.resolveNamePath(companyHome, pathElements);
NodeRef template = templateFile.getNodeRef();
List<String> users = new ArrayList<String>();
users.add(userName);
ActionService actionService = serviceRegistry.getActionService();
Action mailAction = actionService.createAction(MailActionExecuter.NAME);
mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
Map<String, Serializable> templateArgs = new HashMap<String, Serializable>();
templateArgs.put("userName", userName);
Map<String, Serializable> templateModel = new HashMap<String, Serializable>();
templateModel.put("args",(Serializable)templateArgs);
mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL,(Serializable)templateModel);
mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Content Notification");
mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, (Serializable) users);
actionService.executeAction(mailAction, null);
} catch (org.alfresco.service.cmr.model.FileNotFoundException e) {
e.printStackTrace();
}
Is there any way to enable this replyTo parameter in alfresco ?
Please help.

I have override the OOTB MailActionExecuter class.
added my code to set the replyTo parameter
I fixed parameter from java class mailAction.setParameterValue(MailActionExecuter.PARAM_REPLY_TO,"myEmail#gmail.com");
and access using
public static final String PARAM_REPLY_TO = "reply_to";
message.setReplyTo(replyTo);

Related

The request was missing an Authentication Key. Please, refer to section "Authentication" with IHttpClientFactory

I'm trying to send an HTTP request from .NET Core 3.1 REST API to another API but below Exception keep appeared Although I'm already added the Authentication Key :
The request was missing an Authentication Key. Please, refer to section "Authentication"
here is my code :
public class AppService
{
private readonly IHttpClientFactory _clientFactory;
string key = "key=llllll ......";
string webAPIKey = "......";
string Id = "......";
public AppService(IHttpClientFactory clientFactory) {
_clientFactory = clientFactory;
}
public async Task<string> sendBroadCastNotification()
{
Data _data = new Data();
_data.title = "test data Ttile";
_data.detail = "test data detail";
Notification _notification = new Notification();
_notification.title = "test notification Ttile";
_notification.body = "test notification body";
MyNotification NotifcationData = new MyNotification {
data=_data,
notification=_notification,
to= "/topics/all"
};
try {
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Add("project_id", Id );
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);
StringContent bodyOfRequest = new StringContent(System.Text.Json.JsonSerializer.Serialize(NotifcationData ), Encoding.UTF8, "application/json");
using var httpResponse =
await client.PostAsync("https://.......", bodyOfRequest);
var result = httpResponse.Content.ReadAsStringAsync().Result;
return result;
}
catch (Exception ex)
{
throw new System.ArgumentException(ex.Message.ToString(), "original");
}
//return null;
}
}
I found the answer here in this link:
I add the key by using the below line:
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", key);
the below way that I was trying to add the authorization header wasn't understandable as an authorization header :
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);

Alfresco: Stream is already closed

I am trying to create text document using apache-chemistry in alfresco. My code is for creating document is
Document document = FileUtils.createTextDocument("/", "test.txt", "test document", BaseTypeId.CMIS_DOCUMENT.value(), VersioningState.MAJOR, session);
when I execute my code I am getting following exception
org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException: Cannot access "http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom/children?id=5717e8a0-61b2-4bcb-8a91-2f4b61ebfefa&versioningState=major": Stream is already closed!
at org.apache.chemistry.opencmis.client.bindings.spi.http.DefaultHttpInvoker.invoke(DefaultHttpInvoker.java:233)
at org.apache.chemistry.opencmis.client.bindings.spi.http.DefaultHttpInvoker.invokePOST(DefaultHttpInvoker.java:68)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.post(AbstractAtomPubService.java:713)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.ObjectServiceImpl.createDocument(ObjectServiceImpl.java:122)
at org.apache.chemistry.opencmis.client.runtime.SessionImpl.createDocument(SessionImpl.java:1165)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:77)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:460)
at org.apache.chemistry.opencmis.client.util.FileUtils.createTextDocument(FileUtils.java:168)
Try this worked fine for me
public static void main(String args[]) {
String serverUrl = args[0];
String username = args[1];
String password = args[2];
Session session = getSession(serverUrl, username, password);
Folder root = session.getRootFolder();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_
DOCUMENT.value());
String name = "New Document (" + System.currentTimeMillis() +
").txt";
properties.put(PropertyIds.NAME, name);
List<Ace> addAces = new LinkedList<Ace>();
List<Ace> removeAces = new LinkedList<Ace>();
List<Policy> policies = new LinkedList<Policy>();
String content = "The quick brown fox jumps over the lazy dog.";
ContentStream contentStream = new ContentStreamImpl("text.txt",
BigInteger.valueOf(content.length()),
"text/plain", new ByteArrayInputStream(content.
getBytes()));
Document newDocument = root.createDocument(properties,
contentStream, VersioningState.MAJOR, policies, addAces, removeAces,
session.getDefaultContext());
System.out.println(newDocument.getId());
}

Get property of person Alfresco in JAVA

I'm using Alfresco 5.1 Community, and i'm trying to get a property value of a current person logged for example, in the user I have:
"{http://www.someco.org/model/people/1.0}customProperty"
How can I obtain this in java?
Is a custom property, so, in http://localhost:8080/alfresco/service/api/people it does not appear. How can I do this?
I try this to obtain at least nodeRef:
protected ServiceRegistry getServiceRegistry() {
ProcessEngineConfigurationImpl config = Context.getProcessEngineConfiguration();
if (config != null) {
// Fetch the registry that is injected in the activiti spring-configuration
ServiceRegistry registry = (ServiceRegistry) config.getBeans().get(ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
if (registry == null) {
throw new RuntimeException("Service-registry not present in ProcessEngineConfiguration beans, expected ServiceRegistry with key" + ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
}
return registry;
}
throw new IllegalStateException("No ProcessEngineConfiguration found in active context");
}
public void writeToCatalina() {
PersonService personService = getServiceRegistry().getPersonService();
System.out.println("test");
String name = AuthenticationUtil.getFullyAuthenticatedUser();
System.out.println(name);
NodeRef personRef = personService.getPerson(name);
System.out.println(personRef);
}
But I got:
No ProcessEngineConfiguration found in active context
Help me !
You can query Alfresco using CMIS and call the API:
GET /alfresco/service/api/people/{userName}.
For first you can define the method to create the session CmisSession:
public Session getCmisSession() {
logger.debug("Starting: getCmisSession()");
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, url + ATOMPUB_URL);
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.AUTH_HTTP_BASIC, "true");
parameter.put(SessionParameter.USER, username);
parameter.put(SessionParameter.PASSWORD, password);
parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
List<Repository> repositories = factory.getRepositories(parameter);
return repositories.get(0).createSession();
}
Then execute the query (this method returns more than one result, you probably need to change it):
public void doQuery(String cql, int maxItems) {
Session cmisSession = getCmisSession();
OperationContext oc = new OperationContextImpl();
oc.setMaxItemsPerPage(maxItems);
ItemIterable<QueryResult> results = cmisSession.query(cql, false, oc);
for (QueryResult result : results) {
for (PropertyData<?> prop : result.getProperties()) {
logger.debug(prop.getQueryName() + ": " + prop.getFirstValue());
}
}
}
If you need to get the token, use this:
public String getAuthenticationTicket() {
try {
logger.info("ALFRESCO: Starting connection...");
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("user", username);
params.put("password", password);
Source result = restTemplate.getForObject(url + AFMConstants.URL_LOGIN_PARAM, Source.class, params);
logger.info("ALFRESCO: CONNECTED!");
XPathOperations xpath = new Jaxp13XPathTemplate();
return xpath.evaluateAsString("//ticket", result);
}
catch (RestClientException ex) {
logger.error("FATAL ERROR - Alfresco Authentication failed - getAuthenticationTicket() - " + ex );
return null;
}
catch (Exception ex) {
logger.error("FATAL ERROR - Alfresco Authentication failed - getAuthenticationTicket() - " + ex );
return null;
}
}
You need to obtain your user noderef using this API then access its properties this way!
Edit : You need to inject service registry on your bean!
String name = AuthenticationUtil.getFullyAuthenticatedUser()
You can use this. Let me know if it works.
This will give you current logged in user name and detail.
String name = AuthenticationUtil.getFullyAuthenticatedUser();
System.out.println("Current user:"+name);
PersonService personService=serviceRegistry.getPersonService();
NodeRef node=personService.getPerson(name);
NodeService nodeService=serviceRegistry.getNodeService();
Map<QName, Serializable> props=nodeService.getProperties(node);
for (Entry<QName, Serializable> entry : props.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}

Java mail getInputStream left recipient

i'm writing a mail send method with javamail.
I can not understand why I get and error as: Recipient not set.
This is my code:
public static void sendMail(String to, String subj, String body, String attachmentName, byte[] attachment, String mime) throws Exception {
Properties p = System.getProperties();
Session session = Session.getInstance(p);
MimeMessage dummyMessage = new MimeMessage(session);
dummyMessage.setFrom(new InternetAddress(LovProvider.getOpzioni().get("mail.address")));
dummyMessage.setSubject(subj);
String[] tos = to.split(";");
Address[] tosAddr = new InternetAddress[tos.length];
for (int i = 0; i < tos.length; i++) {
tosAddr[i] = new InternetAddress(tos[i]);
}
dummyMessage.setRecipients(Message.RecipientType.TO, tosAddr);
Multipart mp = new MimeMultipart();
MimeBodyPart bp = new MimeBodyPart();
bp.setText(body);
mp.addBodyPart(bp);
if (attachmentName != null && attachment != null) {
DataSource dataSource = new ByteArrayDataSource(attachment, mime);
MimeBodyPart attachBodyPart = new MimeBodyPart();
attachBodyPart.setDataHandler(new DataHandler(dataSource));
attachBodyPart.setFileName(attachmentName);
mp.addBodyPart(attachBodyPart);
}
dummyMessage.setContent(mp);
//***** DEBUGGING here I find the recipient
sendMail(dummyMessage.getInputStream());
}
public static void sendMail(InputStream emlFile) throws Exception {
Properties props = System.getProperties();
props.put("mail.host", LovProvider.getOpzioni().get("mail.out.host"));
props.put("mail.transport.protocol", LovProvider.getOpzioni().get("mail.out.protocol"));
props.put("mail." + LovProvider.getOpzioni().get("mail.out.protocol") + ".port", LovProvider.getOpzioni().get("mail.out.port"));
Session mailSession = Session.getDefaultInstance(props, PasswordAuthentication.getAuth(LovProvider.getOpzioni().get("mail.out.user"), LovProvider.getOpzioni().get("mail.out.password")));
MimeMessage message = new MimeMessage(mailSession, emlFile);
//***** DEBUGGING here I CAN NOT find the recipient
Transport.send(message);
}
As I wrote in comments in debug mode i can see the recipient correctly set in the first part, whant i convert it to InputStream to the second method I can not find recipient anymore.
I can't debugging your code, but maybe this examples can help you:
Examples about sending/receiving mail via/from gmail
http://famulatus.com/component/search/?searchword=gmail&searchphrase=all&Itemid=9999

Send Email From Amazon SES in ASP.NET MVC App

I host my web app which is written in .net mvc2 on amazon ec2. currrently use gmail smtp to send email. beacuse of google for startup email quota cant send more than 500 email a day. So decide to move amazon ses. How can use amazon ses with asp.net mvc2? How about configuration etc? Is email will send via gmail? because our email provider is gmail. etc.
Send Email via Amazon is a right decision. Because when you move to amazon you will immediately get 2000 email free per day which is greater than googla apps 500 emails quota a day.
Step by Step:
Go to http://aws.amazon.com/ses
and click Sign Up for Amazon SES.
To get your AWS access identifiers
verify your email address - email
which you will send email via. You
need perl packages installled on
your computer to test email
features.
include:amazonses.com to your dns record.
Step by step documentation.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/getting-started.html
There is a Amazon SES (Simple Email Service) C# Wrapper on codeplex you can use this wrapper to send emails.
Amazon SES C# Wrapper
Easiest way is to download the SDK via Nuget (package is called AWSSDK) or download the SDK from Amazon's site. The sdk download from their site has an example project that shows you how to call their API to send email. The only configuration is plugging in your api keys. The trickiest part is verifying your send address (and any test receipients) but their is an API call there too to send the test message. You will then need to log in and verify those email addresses. The email will be sent through Amazon (that is the whole point) but the from email address can be your gmail address.
#gandil I created this very simple code to send emails
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using System.IO;
namespace SendEmail
{
class Program
{
static void Main(string[] args)
{
//Remember to enter your (AWSAccessKeyID, AWSSecretAccessKey) if not using and IAM User with credentials assigned to your instance and your RegionEndpoint
using (var client = new AmazonSimpleEmailServiceClient("YourAWSAccessKeyID", "YourAWSSecretAccessKey", RegionEndpoint.USEast1))
{
var emailRequest = new SendEmailRequest()
{
Source = "FROMADDRESS#TEST.COM",
Destination = new Destination(),
Message = new Message()
};
emailRequest.Destination.ToAddresses.Add("TOADDRESS#TEST.COM");
emailRequest.Message.Subject = new Content("Hello World");
emailRequest.Message.Body = new Body(new Content("Hello World"));
client.SendEmail(emailRequest);
}
}
}
}
You can find the code in here https://github.com/gianluis90/amazon-send-email
Download AWSSDK.dll file from internet
use following name-spaces
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using System.Net.Mail;
2 . Add to web config...
<appSettings>
<add key="AWSAccessKey" value="Your AWS Access Key" />
<add key="AWSSecretKey" value="Your AWS secret Key" />
</appSettings>
3 . Add a AWSEmailSevice class to your project that will allow to send mail via AWS ses...
public class AWSEmailSevice
{
//create smtp client instance...
SmtpClient smtpClient = new SmtpClient();
//for sent mail notification...
bool _isMailSent = false;
//Attached file path...
public string AttachedFile = string.Empty;
//HTML Template used in mail ...
public string Template = string.Empty;
//hold the final template data list of users...
public string _finalTemplate = string.Empty;
//Template replacements varibales dictionary....
public Dictionary<string, string> Replacements = new Dictionary<string, string>();
public bool SendMail(MailMessage mailMessage)
{
try
{
if (mailMessage != null)
{
//code for fixed things
//from address...
mailMessage.From = new MailAddress("from#gmail.com");
//set priority high
mailMessage.Priority = System.Net.Mail.MailPriority.High;
//Allow html true..
mailMessage.IsBodyHtml = true;
//Set attachment data..
if (!string.IsNullOrEmpty(AttachedFile))
{
//clear old attachment..
mailMessage.Attachments.Clear();
Attachment atchFile = new Attachment(AttachedFile);
mailMessage.Attachments.Add(atchFile);
}
//Read email template data ...
if (!string.IsNullOrEmpty(Template))
_finalTemplate = File.ReadAllText(Template);
//check replacements ...
if (Replacements.Count > 0)
{
//exception attached template..
if (string.IsNullOrEmpty(_finalTemplate))
{
throw new Exception("Set Template field (i.e. file path) while using replacement field");
}
foreach (var item in Replacements)
{
//Replace Required Variables...
_finalTemplate = _finalTemplate.Replace("<%" + item.Key.ToString() + "%>", item.Value.ToString());
}
}
//Set template...
mailMessage.Body = _finalTemplate;
//Send Email Using AWS SES...
var message = mailMessage;
var stream = FromMailMessageToMemoryStream(message);
using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(
ConfigurationManager.AppSettings["AWSAccessKey"].ToString(),
ConfigurationManager.AppSettings["AWSSecretKey"].ToString(),
RegionEndpoint.USWest2))
{
var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
var response = client.SendRawEmail(sendRequest);
//return true ...
_isMailSent = true;
}
}
else
{
_isMailSent = false;
}
}
catch (Exception ex)
{
throw ex;
}
return _isMailSent;
}
private MemoryStream FromMailMessageToMemoryStream(MailMessage message)
{
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
MemoryStream stream = new MemoryStream();
ConstructorInfo mailWriterContructor =
mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
MethodInfo sendMethod =
typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
if (sendMethod.GetParameters().Length == 3)
{
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null); // .NET 4.x
}
else
{
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null); // .NET < 4.0
}
MethodInfo closeMethod =
mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
return stream;
}
}
Use above class to send mail anyone with attachment and template varibales replacement (it's optional)
// Call this method to send your email
public string SendEmailViaAWS()
{
string emailStatus = "";
//Create instance for send email...
AWSEmailSevice emailContaint = new AWSEmailSevice();
MailMessage emailStuff = new MailMessage();
//email subject..
emailStuff.Subject = "Your Email subject";
//region Optional email stuff
//Templates to be used in email / Add your Html template path ..
emailContaint.Template = #"\Templates\MyUserNotification.html";
//add file attachment / add your file ...
emailContaint.AttachedFile = "\ExcelReport\report.pdf";
//Note :In case of template
//if youe want to replace variables in run time
//just add replacements like <%FirstName%> , <%OrderNo%> , in HTML Template
//if you are using some varibales in template then add
// Hold first name..
var FirstName = "User First Name";
// Hold email..
var OrderNo = 1236;
//firstname replacement..
emailContaint.Replacements.Add("FirstName", FirstName.ToString());
emailContaint.Replacements.Add("OrderNo", OrderNo.ToString());
// endregion option email stuff
//user OrderNo replacement...
emailContaint.To.Add(new MailAddress("TOEmail#gmail.com"));
//mail sent status
bool isSent = emailContaint.SendMail(emailStuff);
if(isSent)
{
emailStatus = "Success";
}
else
{
emailStatus = "Fail";
}
return emailStatus ; }
Following is how I sent email with attachment
public static void SendMailSynch(string file1, string sentFrom, List<string> recipientsList, string subject, string body)
{
string smtpClient = "email-smtp.us-east-1.amazonaws.com"; //Correct it
string conSMTPUsername = "<USERNAME>";
string conSMTPPassword = "<PWD>";
string username = conSMTPUsername;
string password = conSMTPPassword;
// Configure the client:
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpClient);
client.Port = 25;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail = new System.Net.Mail.MailMessage();
mail.From = new MailAddress(sentFrom);
foreach (string recipient in recipientsList)
{
mail.To.Add(recipient);
}
mail.Bcc.Add("test#test.com");
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
Attachment attachment1 = new Attachment(file1, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment1.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file1);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file1);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file1);
mail.Attachments.Add(attachment1);
client.Send(mail);
}

Resources