Writing an encrypted mail via Exchange Web Services - email

I would like to send an encrypted EMail Message with Exchange WEb Services using C#.
Is there any possibillity?
Thanks
Edit:
My Mail body encrypter:
public static byte[] encry(string body, ContentTyp typ, string to )
{
X509Certificate2 cert = GetMailCertificate(to);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString()));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
envelope.Encrypt(recipient);
//System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode());
return envelope.Encode();
}
Main
byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test#server.com");
EmailMessage msg1 = new EmailMessage(_server);
msg1.MimeContent = new MimeContent("UTF-8", con);
msg1.ToRecipients.Add("user#server.com");
msg1.InternetMessageHeaders = ??
msg1.Send();

If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message.
Using the EWS Managed API, this can be done as follows:
var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();
EDIT:
You should add the standard headers like From, To, Date, Subject, etc. And the content-type.
Subject: Test
From: "sender" <sender#yourcompany.com>
To: "recipient" <recipient#othercompany.com>
Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m
Your encrypted body goes here
Just use a StringWriter put all that together. The result is your MIME body.

Related

Hybris EmailService where configure credentials

I'm using EmailService in order to send a basic email:
String subject = request.getParameter("subject");
String body = request.getParameter("body");
EmailAddressModel fromAddress = modelService.create(EmailAddressModel.class);
fromAddress.setDisplayName("test#test.es");
fromAddress.setEmailAddress("test#test.es");
List<EmailAddressModel> addresses = new ArrayList<>();
addresses.add(fromAddress);
EmailMessageModel email = modelService.create(EmailMessageModel.class);
email.setSubject(subject);
email.setBody(body);
email.setToAddresses(addresses);
email.setFromAddress(fromAddress);
email.setReplyToAddress("myaccount#gmail.com");
modelService.save(email);
emailService.send(email);
Where do I configure the password of "myaccount#gmail.com" in order to make the Hybris SMTP server authentificate with my personal mail and send the email?
You can configure below parameters in local.properties file or you can change them in hac for runtime only.
mail.smtp.server
mail.smtp.port
mail.smtp.user
mail.smtp.password
mail.pop3.beforesmtp
mail.pop3.password
mail.pop3.server
mail.pop3.user
mail.from
mail.replyto
mail.use.tls
You can get more detail from blog post.

Jmeter Groovy JavaMail API multipart add content to sample result

Looking at answers posted in Reading Emails based on recipient email id in Jmeter using groovy I actually managed to use the recipient search term.
Using the below in a JSR223 Sampler
import javax.mail.Multipart
import javax.mail.internet.MimeMultipart
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties()
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX')
inbox.open(javax.mail.Folder.READ_ONLY)
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')) // i.e. test+1#gmail.com
onlyFromGivenUser.each { message ->
if (message.getContent() instanceof Multipart) {
StringBuilder content = new StringBuilder()
def multipart = (Multipart) message.getContent()
multipart.eachWithIndex { Multipart entry, int i ->
def part = entry.getBodyPart(i)
if (part.isMimeType('text/plain')) {
content.append(part.getContent().toString())
}
}
SampleResult.setResponseData(content.toString(), 'UTF-8')
} else {
SampleResult.setResponseData(message.getContent().toString(), 'UTF-8')
}
}
This works perfectly, but fails when email is ContentType: multipart/MIXED as it does not drill down to multipart/RELATED, multipart/ALTERNATIVE and then to TEXT/PLAIN or TEXT/HTML, on which I like to do a regex on to extract a link from the body.
Guessing some counter on i is needed and an "if else", or something like mentioned here, but unsure how to convert to fit in the above script...
Any help would be much appreciated.
I stepped away from javax.mail.Multipart and javax.mail.internet.MimeMultipart and have implemented the below code in a While Controller
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties();
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX');
inbox.open(javax.mail.Folder.READ_ONLY);
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')); // i.e. test+1#gmail.com
try {
onlyToGivenUser.each { message ->
ByteArrayOutputStream emailRaw = new ByteArrayOutputStream();
message.writeTo(emailRaw);
SampleResult.setResponseData(emailRaw.toString(), 'UTF-8');
}
} catch (Exception ex) {
log.warn("Something went wrong", ex);
throw ex;
}
Hope this helps someone one day.

How would you attach an excel document using MailJet api

Hello I have tried using mailjets api to send an excel document.
I first encode the excel file to base64 using mailjets library.
I then use mailjets library to add the file as an attachment and set the mime type application/vnd.ms-excel.
Heres an example.
request = new MailjetRequest(Emailv31.resource)
.property(Emailv31.MESSAGES, new JSONArray()
.put(new JSONObject()
.put(Emailv31.Message.FROM, new JSONObject()
.put("Email", "pilot#mailjet.com")
.put("Name", "Mailjet Pilot"))
.put(Emailv31.Message.TO, new JSONArray()
.put(new JSONObject()
.put("Email", "passenger1#mailjet.com")
.put("Name", "passenger 1")))
.put(Emailv31.Message.SUBJECT, "Your email flight plan!")
.put(Emailv31.Message.TEXTPART, "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!")
.put(Emailv31.Message.HTMLPART, "<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!")
.put(Emailv31.Message.ATTACHMENTS, new JSONArray()
.put(new JSONObject()
.put("ContentType", "application/vnd.ms-excel")
.put("Filename", "test.txt")
.put("Base64Content", "excelFileBase64")))));
response = client.post(request);
However I always receive the file as its string represented base64 encoded.
Use ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
and test.xlsx

Error empty content gmail using javamail api send email smtp

I'm working project : jsf, richfaces. I has just updated javamail api newest version 1.5.5 at https://java.net/projects/javamail/pages/Home
When i test send email from gmail to my gmail,
Subject : Subject test.
Content : Content test. And config : smtp.gmail.com, 465, SSL.
It has just subject and no content in my inbox receive gmail :
And log :
And my code :
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Set the host smtp address
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
.......
.......
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setText("UTF8");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(SMTP_AUTH_USER);
msg.setFrom(addressFrom);
System.out.println(addressFrom);
msg.setSubject(subject, "utf-8");
......
......
try {
String content = replaceCharacterInEmail(cus, null,null, message);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(content, "text/html; charset=utf-8");
// attach the file to the message
Multipart mp = new MimeMultipart();
int count = 0;
if(files != null){
while (count < files.size()) {
MimeBodyPart mbdp = new MimeBodyPart();
mbdp.attachFile(files.get(count));
mp.addBodyPart(mbdp);
count++;
}
}
// create the Multipart and add its parts to it
mp.addBodyPart(mbp1);
// add the Multipart to the message
msg.setContent(mp);
Transport.send(msg);
} catch (Exception e) {
invalidAddress += (", " + address.trim());
e.printStackTrace();
}finally{
if (!"".equals(emailFails)) {
emailFails = emailFails.substring(1);
}
}
But, when i test above code at another project test (java application) with above lib javamail. It's ok :
.
I don't think problem at version of lib javamail. I don't know different between 2 project, because part send email is similar. How can i fix that error ?
Please observe this email structure:
-- multipart/mixed
-- mutlipart/alternative
-- text/plain
-- text/html
-- application/octet-stream (or any other mimetypes)
I found problem is conflict library at lib of jboss server and lib of app.ear (deploy).

Salesforce rest api INVALID_SESSION_ID

I'm trying to connect my asp.net REST api to salesforce. I'm succesfully going through authentification, but when I start to send POST requests, I'm getting an error
{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}
Here is my POST request:
//SFServerUrl = "https://na17.salesforce.com/services/";
//url = "data/v28.0/sobjects/Account";
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postBody);
HttpWebRequest request = WebRequest.Create(Globals.SFServerUrl + url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = postBytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
HttpCookie cookie = HttpContext.Current.Request.Cookies[Globals.SFCookie];
var ticket = FormsAuthentication.Decrypt(cookie.Value);
string authToken = ticket.UserData;
request.Headers.Add("Authorization", "Bearer " + authToken);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
return new Tuple<bool, string>(true, sb.ToString());
When I'm trying to send GET request - I recieve 200 response.
Also, I've tried to send a POST Request with the same token from Simple Rest Client and it get's 200 response. I tried to change my "Authorization : Bearer" Header to "Authorization : Oauth", but nothing changed. I also tried to catch this error, get refresh token and send a request again with refreshed token, but nothing changed. Please, help me with this.
Using workbench I was able to POST the following JSON to /services/data/v29.0/sobjects/Account and create a new Account.
{
"Name" : "Express Logistics and Transport"
}
Raw Response
HTTP/1.1 201 Created
Date: Sun, 07 Sep 2014 21:32:06 GMT
Set-Cookie: BrowserId=_HC-bzpTQABC1237vFu2hA;Path=/;Domain=.salesforce.com;Expires=Thu, 06-Nov-2014 21:32:06 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Sforce-Limit-Info: api-usage=209/15000
Location: /services/data/v29.0/sobjects/Account/0010000000000001AAA
Content-Type: application/json;charset=UTF-8
Content-Encoding: gzip
Transfer-Encoding: chunked
{
"id" : "0010000000000001AAA",
"success" : true,
"errors" : [ ]
}
Things to check:
Your URL. It appears to be missing the leading /services
Is SFServerUrl the same Salesforce pod/server that the Session Id was issued to? If the Session Id came from another pod then it would be invalid on na17.
How did you create the Session Id? If you used OAuth, what scopes did you request?
Is the Session Id coming out of the cookie valid?
Has something else using the same Session Id called logout and invalidated the session?
Incidentally, the Salesforce StackExchange site is a great place to ask Salesforce specific questions.
See also:
Using REST API Resources - Create a Record
The problem was that I added Headers after Content. When I switched these lines of code everything worked.