I'm trying to send email with inline attachment using MS Graph. I know how to send email without attachment but when I'm trying to send message with attachment I don't know how can I add this attachment to the message.
Here is my code:
// recipients
Recipient recipient = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = "tom#mail.com";
recipient.emailAddress = emailAddress;
List<Recipient> recipients = List.of(recipient);
// body
ItemBody body = new ItemBody();
body.contentType = BodyType.HTML;
body.content = "<html><body>my image:<br><img src='cid:my_image_CID'></body></html>";
// inline image
Attachment attachment = new Attachment();
attachment.isInline = true;
attachment.contentType = ".png";
attachment.id = "my_image_CID";
//attachment.contentBytes - I DON'T SEE THIS FIELD...
// message
Message message = new Message();
message.subject = "my subject";
message.body = body;
message.toRecipients = recipients;
//message.attachments = ??? - how to create this object?
there are examples in the internet that I can set attachment.contentBytes but I don't see this attribute.
For the message I can set attachments object which is of type
AttachmentCollectionPage
but I don't know how can I create this object.
I'm using the following versions:
Microsoft Graph Java SDK » 5.42.0
Microsoft Graph Java Core SDK » 2.0.14
You need to use FileAttachment which extends Attachment and has property contentBytes.
Related
I want to write a service through which I can create a email message with (to, cc, bcc, subject, body) specified. Then I need to return this email message to front end and download it in ".oft" format, in such a way that when I click on this downloaded file; file should open with all the fields (to, cc, bcc, subject, body) populated.
I am using Java as backend technology and angular5 as front-end.
I have tried using javax.mail utility to create the email message and return it as byte array. Something like:
Properties prop = System.getProperties();
Session session = Session.getDefaultInstance(prop, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("emailAddr#domain.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("emailAddr#domain.com"));
msg.setSentDate(new Date());
msg.setSubject("subject");
msg.setText("text of msg");
//return it from service API as
response.getOutputStream().write(msg.toString().getBytes());
On front end (component.ts file) I am retrieving the response as :
//function gets called on button click
createEmailTemplate():void{
this.httpService.getEmail('serviceUrl')
.subscribe(
email => {
let filename = "SampleMailFile.oft";
let linkElement = document.createElement('a');
let blob = new Blob([email], { type: "message/rfc822"});
let url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
let clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
);
}
A MSG file is supposed to have the same format as an OFT file. If that’s true then you should be able to use jotlmsg to generate the file. You shouldn’t need to use JavaMail at all for this, since it’s intended to actually send the mail.
NOTE: I’ve not used this library before, so I can’t speak to whether this will truly work.
Test Java API for IBM Watson discovery service
Discovery discovery = new Discovery("2017-09-01");
System.out.println("Creating a new document...");
String documentJson = "{\"field\":\"value\"}";
InputStream documentStream = new ByteArrayInputStream(documentJson.getBytes());
AddDocumentOptions.Builder createDocumentBuilder =
new AddDocumentOptions.Builder(environmentId, collectionId);
createDocumentBuilder.file(documentStream).fileContentType( HttpMediaType.APPLICATION_JSON);
DocumentAccepted createDocumentResponse = discovery.addDocument(createDocumentBuilder.build()).execute();
Should work without throwing any exception.
An exception is thrown on the last statment "discovery.addDocument"; error message is "filename cannot be null when file is not null"
Since you are using documentJson parameter, are you sure that JSON metadata has fileName. If not define a string with variable name fileName.
FYR Add Document to Discovery
Discovery discovery = new Discovery("2017-11-07");
discovery.setEndPoint("https://gateway.watsonplatform.net/discovery/api/");
discovery.setUsernameAndPassword("{username}", "{password}");
String environmentId = "{environment_id}";
String collectionId = "{collection_id}";
String documentId = "{document_id}";
String fileName = "<fileName>";
FYI - You cannot use documentStream and fileName parameter together
I'm using a DocuSign Java SDK and need the functionality of CarbonCopy as I need to send every document to a person within our company other than a Signer.
So when I use the gmail address for the Signer the email is sent. But when I use the gmail address for the CarbonCopy recipient the email is never sent and I do not get an error. The envelope id is returned as if everything went fine.
Is there anything that I'm missing? Is it possible to make that work?
// login call available off the AuthenticationApi
AuthenticationApi authApi = new AuthenticationApi();
// login has some optional parameters we can set
AuthenticationApi.LoginOptions loginOps = authApi.new LoginOptions();
loginOps.setApiPassword("true");
loginOps.setIncludeAccountIdGuid("true");
LoginInformation loginInfo = authApi.login(loginOps);
// note that a given user may be a member of multiple accounts
List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
String accountId = loginAccounts.get(0).getAccountId();
Path path = Paths.get(sFilePath);
byte[] PDFContents = Files.readAllBytes(path);
// Create an envelope that will store the document(s), field(s), and recipient(s)
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please sign this document sent from Java SDK)");
// Add a document to the envelope
Document doc = new Document();
String base64Doc = DatatypeConverter.printBase64Binary(PDFContents);
doc.setDocumentBase64(base64Doc);
doc.setName("MaterialRequisition.pdf"); // can be different from actual file name
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// add a recipient to sign the document, identified by name and email we used above
Signer signer = new Signer();
signer.setEmail(sApproverEmail);
signer.setName(sApproverName);
signer.setRecipientId("1");
CarbonCopy cc = new CarbonCopy();
cc.setEmail(sCCEmail);
cc.setName(sCCName);
cc.setRecipientId("2");
// create a signHere tab somewhere on the document for the signer to sign
// default unit of measurement is pixels, can be mms, cms, inches also
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("710");
// Can have multiple tabs, so need to add to envelope as a single element list
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// add recipients (in this case a single signer) to the envelope
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
envDef.getRecipients().getCarbonCopies().add(cc);
// send the envelope by setting |status| to "sent". To save as a draft set to "created"
envDef.setStatus("sent");
// instantiate a new EnvelopesApi object
EnvelopesApi envelopesApi = new EnvelopesApi();
// call the createEnvelope() API to send the signature request!
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
logger.debug("Envelope Id "+ envelopeSummary.getEnvelopeId());
// Delete the PDF file that Logi generated
Files.delete(path);
CarbonCopy recipients will receive email only when the envelope gets completed by all the parties based on the recipient’s order. Have a look at the Carbon Copies Recipient description in this link.
Debug the code and make sure whether CarbonCopy values gets added inside the envDef.getRecipients().getCarbonCopies() before it hits the createEnvelope and when the full envelope process gets completed by the signer thereafter a copy will be sent to the carbon copy recipient mail address, to make sure of that sign into the CarbonCopy recipient email address an email must be received along with completed document where you can only view the document..
i have several .pst files and need all the mail-addresses, i sent mails to. The example code of the library allows me to traverse every mail in the file, but i can't find the right getter to extract the mail address of the receiver.
To traverse every mail, i use the code from this site:
https://code.google.com/p/java-libpst/
PSTMessage email = (PSTMessage) folder.getNextChild();
while (email != null) {
printDepth();
System.out.println("Email: " + email.getSubject());
printDepth();
System.out.println("Adress: " + email.getDisplayTo());
email = (PSTMessage) folder.getNextChild();
}
The getDisplayTo() method only displays the receivers names but not their mail addresses.
What getter do i need to use to get the addresses?
Best,
Michael
First method : : available getters
getSenderEmailAddress
getNumberOfRecipients
getRecipient(int)
Second Method : parse the header and collect the email address (a_sHeader is a string)
Session s = Session.getDefaultInstance(new Properties());
InputStream is = new ByteArrayInputStream(a_sHeader.getBytes());
try {
m_message = new MimeMessage(s, is);
m_message.getAllHeaderLines();
for (Enumeration<Header> e = m_message.getAllHeaders(); e.hasMoreElements();) {
Header h = e.nextElement();
// Recipients
if (h.getName().equalsIgnoreCase(getHeaderName(RecipientType.REC_TYPE_TO))) {
m_RecipientsTo = processAddresses(h.getValue());
}
...
}
} catch (MessagingException e1) {
...
}
I am using Amazon Simple Email Service java API to send mail to receivers.
I am sending URL in mail body inside tag.
My use case demands the user to double click on the URL received to prompt some action. (like confirmation mail)
Problem is the url gets encoded while receiving. On double clicking it gives page not found (404) error.
Original URL : http://something.com/confirm/email=abc#hotmail.com®Key=somekey&confirm=true
When i double click on this URL on mail, the link is opened in address bar as :
http://something.com/confirm/email=abc%40hotmail.com%26regKey=somekey%26confirm=true
I am using AmazonSimpleEmailServiceClient. Code is below :
SendEmailRequest request = new SendEmailRequest().withSource(sourceAddress);
String confirmationURL="http://something.com/confirm/email=abc#hotmail.com®Key=somekey&confirm=true";
List<String> toAddresses = new ArrayList<String>();
toAddresses.add(toEmail);
Destination dest = new Destination().withToAddresses(toAddresses);
request.setDestination(dest);
Content subjContent = new Content().withData("Confirmation Request");
Message msg = new Message().withSubject(subjContent);
// Include a body in both text and HTML formats
Content textContent = new Content().withData("Dear please go to the following URL:"+
confirmationURL+"\n\n");
Content htmlContent = new Content().withData("<p>Dear please go to the following URL:</p>"+
"<p>"+confirmationURL+"</p>");
Body body = new Body().withHtml(htmlContent).withText(textContent);
msg.setBody(body);
request.setMessage(msg)
UPDATE
Just found, this problem is occurring only when recipient email is in hotmail.com. Why microsoft always have to do something differently ? Somebody help !
Use the class java.net.URLEncoder:
String confirmationURL = URLEncoder.encode( "http://something.com/confirm/email=abc#hotmail.com®Key=somekey& confirm=true", "UTF-8");