When I try to send a message using Microsoft Graph Java API, It's state is Draft.
Authentication.initialize(appId);
final String accessToken = Authentication.getUserAccessToken(appScopes);
authProvider = new SimpleAuthProvider(accessToken);
// Create default logger to only log errors
DefaultLogger logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.DEBUG);
// Build a Graph client
graphClient = GraphServiceClient.builder()
.authenticationProvider(authProvider)
.logger(logger)
.buildClient();
IMailFolderDeltaCollectionPage mailFolderCollectionPage = graphClient.me().mailFolders().delta()
.buildRequest().get();
AtomicReference<String> inBoxFolderId = new AtomicReference<>("");
while (mailFolderCollectionPage.getNextPage() != null) {
List<MailFolder> mailFolders = mailFolderCollectionPage.getCurrentPage();
mailFolders.forEach(m -> {
if (m.displayName.equals("Inbox")) {
inBoxFolderId.set(m.id);
}
});
mailFolderCollectionPage = mailFolderCollectionPage.getNextPage().buildRequest().get();
}
IMessageDeltaCollectionPage messageCollectionPage = graphClient.me().mailFolders("Inbox")
.messages().delta().buildRequest().get();
Message backedMessaged = null;
while (messageCollectionPage.getNextPage() != null) {
System.out.println("messageCollectionPage = " + messageCollectionPage);
List<Message> messageList = messageCollectionPage.getCurrentPage();
backedMessaged = messageList.get(0);
break;
}
graphClient.me().mailFolders("Inbox").messages().buildRequest().post(backedMessaged);
When you create an Outlook message, its state will remain as draft until you send it. You should use the send request to send your message. It will then not be marked as draft anymore.
Look here for more informations : https://learn.microsoft.com/fr-fr/graph/api/message-send?view=graph-rest-1.0&tabs=http
Related
I found out a message sent via AnswerInlineQuery can be edited by EditMessageText() in "supergroup" chats only.
The created group by default has the "group" type, but after changing any settings, it changes to "supergroup" (I read this from the documentation).
Next, I changed the chat where I couldn't edit the message sent via AnswerInlineQuery to "supergroup" and it worked. There is no information about the group type in the telegram client itself.
Also, the message sent via AnswerInlineQuery to the "private" type chat is not editable too. Haven't tried channels.
And messages sent via SendMessage() are edited without problems in any chat type, the main thing is to catch the messageID.
Is it library limitation, or it's not possible for API in common?
private final TelegramBot bot = new TelegramBot(System.getenv("TG_BOT_TOKEN"));
long chatID;
int messageID;
public void listen() {
this.bot.setUpdatesListener(updates -> {
updates.forEach(this::process);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
}
#SuppressWarnings("unchecked")
private void process(Update update) {
Message message = update.message();
InlineQuery inlineQuery = update.inlineQuery();
BaseRequest request = null;
if (message != null && message.viaBot() != null) {
chatID = message.chat().id();
messageID = message.messageId();
request = new EditMessageText(chatID, messageID, String.valueOf(update.message().messageId()));
}
if (inlineQuery != null) request = new AnswerInlineQuery(inlineQuery.id(), new InlineQueryResultArticle("id", "title", "text"));
if (request != null) bot.execute(request);
}
}```
With the following code I am able to read the template from my account and send an email with that template is working.
EnvelopesApi envelopesApi1 = createEnvelopesApi(basePath,
prop.getProperty("authenticationToken"));
EnvelopeDefinition envelope1 = makeEnvelope(signerEmail, signerName);
EnvelopeSummary result = envelopesApi1.createEnvelope(accountId, envelope1);
// session.setEnvelopeId(result.getEnvelopeId());
DoneExample.createDefault("Cusotm title")
.withJsonObject(result)
.withMessage("The envelope has been created and sent!<br/>Envelope ID "
+ result.getEnvelopeId() + ".")
.addToModel(model);
But my application is embedded application, so the approval needs to be done over application Hence I have tried to integrate the same in my embedded application.But I am getting error. My code is below.
// Next, create the top level envelope definition and populate it.
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
envelopeDefinition.setEmailSubject("Please sign this document!!");
envelopeDefinition.setEmailBlurb("this is the custom mail content");
//envelopeDefinition.setDocuments(Arrays.asList(document));
envelopeDefinition.setTemplateId("6fcd32d8-91f6-4f4f-90f8-8b54eb71bfb8");
envelopeDefinition.setTemplateRoles(Arrays.asList(signer1));
// Add the recipient to the envelope object
Recipients recipients = new Recipients();
//recipients.setSigners(Arrays.asList(signer));
//envelopeDefinition.setRecipients(recipients);
envelopeDefinition.setStatus("sent");
// requests that the envelope be created and sent.
// Step 2. Call DocuSign to create and send the envelope
ApiClient apiClient = new ApiClient(basePath);
apiClient.setAccessToken(accessToken, tokenExpirationSeconds);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient);
EnvelopeSummary results = envelopesApi.createEnvelope(accountId, envelopeDefinition);
String envelopeId = results.getEnvelopeId();
// Step 3. The envelope has been created.
// Request a Recipient View URL (the Signing Ceremony URL)
RecipientViewRequest viewRequest = new RecipientViewRequest();
// Set the url where you want the recipient to go once they are done signing
// should typically be a callback route somewhere in your app.
viewRequest.setReturnUrl(baseUrl + "/ds-return");
viewRequest.setAuthenticationMethod(authenticationMethod);
viewRequest.setEmail(signerEmail);
viewRequest.setUserName(signerName);
viewRequest.setClientUserId(clientUserId);
// call the CreateRecipientView API
ViewUrl results1 = envelopesApi.createRecipientView(accountId, envelopeId, viewRequest);
// Step 4. The Recipient View URL (the Signing Ceremony URL) has been received.
// The user's browser will be redirected to it.
String redirectUrl = results1.getUrl();
redirect = new RedirectView(redirectUrl);
redirect.setExposeModelAttributes(false);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return redirect;
}
Here I am getting the below error.
com.docusign.esign.client.ApiException:
Error while requesting server, received a non successful
HTTP code 400 with response Body:
'{"errorCode":"UNKNOWN_ENVELOPE_RECIPIENT",
"message":"The recipient you have identified is not a valid
recipient of the specified envelope."}'
at com.docusign.esign.client.ApiClient.invokeAPI(ApiClient.java:1177)
~[docusign-esign-java-3.2.0.jar:na]
at com.docusign.esign.api.EnvelopesApi.createRecipientView(EnvelopesApi.java:1262)
~[docusign-esign-java-3.2.0.jar:na]
....
There are two ways to solve this problem, one is my below alternate way and the second one is as Larry suggested in the comment just add the clientUserId to the signer recipient when you send the envelope.
For embedded sign we need to go for CompositeTemplate
private EnvelopeDefinition makeEnvelope(String signerEmail, String signerName, String clientUserId, WorkArguments args) throws IOException {
CarbonCopy cc1 = new CarbonCopy();
cc1.setEmail("mail");
cc1.setName("name");
cc1.setRoleName(EnvelopeHelpers.CC_ROLE_NAME);
cc1.setRecipientId("2");
// create a composite template for the server template
CompositeTemplate compTemplate1 = new CompositeTemplate();
compTemplate1.setCompositeTemplateId("1");
ServerTemplate serverTemplates = new ServerTemplate();
serverTemplates.setSequence("1");
serverTemplates.setTemplateId("dafgs345-546sdf4-3546sdfqew");
compTemplate1.setServerTemplates(Arrays.asList(serverTemplates));
// Add the roles via an inlineTemplate object
InlineTemplate inlineTemplate = new InlineTemplate();
inlineTemplate.setSequence("1");
inlineTemplate.setRecipients(EnvelopeHelpers.createRecipients(createSigner(signerEmail,signerName,clientUserId), cc1));
compTemplate1.setInlineTemplates(Arrays.asList(inlineTemplate));
// The signer recipient for the added document with a tab definition
Tabs signer1Tabs = EnvelopeHelpers.createSingleSignerTab("**signature_1**", ANCHOR_OFFSET_Y, ANCHOR_OFFSET_X);
signer1Tabs.textTabs(Arrays.asList(
createText("text", "453", "110","Customized data"),
createText("numbersOnly", "453", "130", "147896")));
Signer signer1AddedDoc = createSigner(signerEmail, signerName,clientUserId);
signer1AddedDoc.setAccessCode("12345");
signer1AddedDoc.setTabs(signer1Tabs);
// Create the HTML document
byte[] htmlDoc = EnvelopeHelpers.createHtmlFromTemplateFile(HTML_DOCUMENT_FILE_NAME, "args", args);
// Create a composite template for the added document and add the recipients via an inlineTemplate
CompositeTemplate compTemplate2 = new CompositeTemplate();
compTemplate2.setCompositeTemplateId("2");
InlineTemplate inlineTemplate2 = new InlineTemplate();
inlineTemplate2.setSequence("2");
inlineTemplate2.setRecipients(EnvelopeHelpers.createRecipients(signer1AddedDoc, cc1));
compTemplate2.setInlineTemplates(Arrays.asList(inlineTemplate2));
compTemplate2.setDocument(EnvelopeHelpers.createDocument(htmlDoc, HTML_DOCUMENT_NAME,
DocumentType.HTML.getDefaultFileExtention(), "1"));
EnvelopeDefinition env = new EnvelopeDefinition();
env.setStatus(EnvelopeHelpers.ENVELOPE_STATUS_SENT);
env.setCompositeTemplates(Arrays.asList(compTemplate1, compTemplate2));
return env;
}
and then we can call the api
EnvelopeDefinition envelope = makeEnvelope(signerEmail, signerName, clientUserId, args);
EnvelopeSummary envelopResults = envelopesApi2.createEnvelope(accountId, envelope);
RecipientViewRequest viewRequest1 = makeRecipientViewRequest(args);
ViewUrl viewUrl = envelopesApi2.createRecipientView(accountId, envelopResults.getEnvelopeId(), viewRequest1);
return new RedirectView(viewUrl.getUrl());
This is a continuation of Java mail listener using Spring Integration : mail isn't received by multiple app instances . I'm using below ImapMailReceiver code :
#Bean
public ImapMailReceiver receiver() {
ImapMailReceiver receiver = new ImapMailReceiver(
"imaps://username:pwd#mail.company.com/INBOX");
receiver.setShouldMarkMessagesAsRead(false);
receiver.setSimpleContent(true);
receiver.setUserFlag("test-flag");
//receiver.setJavaMailProperties(javaMailProperties());
return receiver;
}
My application has been deployed in dev and stage servers.As per the debug logs : This email server does not support RECENT or USER flags. Hence whatever userflag i'm setting via above code isn't useful and mails will be received by only once instance of my application (either dev or stage ) and not all instances.So mails are getting dropped by one instance. How to make it work so that all of my application instances receives new emails? Should i set any javamail properties ? How to make it work
UPDATE used below custom searchTermStrategy . For every poll list of new messages + set of old messages will be received . Haven't tested on multiple application instances yet.
private class CustomSearchTermStrategy implements SearchTermStrategy {
CustomSearchTermStrategy() {
}
#Override
public SearchTerm generateSearchTerm(Flags supportedFlags, Folder folder) {
SearchTerm searchTerm = null;
boolean recentFlagSupported = false;
if (supportedFlags != null) {
recentFlagSupported = supportedFlags.contains(Flags.Flag.RECENT);
if (recentFlagSupported) {
searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
}
if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
NotTerm notAnswered = new NotTerm(new FlagTerm(new Flags(Flags.Flag.ANSWERED), true));
if (searchTerm == null) {
searchTerm = notAnswered;
} else {
searchTerm = new AndTerm(searchTerm, notAnswered);
}
}
if (supportedFlags.contains(Flags.Flag.DELETED)) {
NotTerm notDeleted = new NotTerm(new FlagTerm(new Flags(Flags.Flag.DELETED), true));
if (searchTerm == null) {
searchTerm = notDeleted;
} else {
searchTerm = new AndTerm(searchTerm, notDeleted);
}
}
if (supportedFlags.contains(Flags.Flag.SEEN)) {
NotTerm notSeen = new NotTerm(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
if (searchTerm == null) {
searchTerm = notSeen;
} else {
searchTerm = new AndTerm(searchTerm, notSeen);
}
}
}
// if (!recentFlagSupported) {
// searchTerm = applyTermsWhenNoRecentFlag(folder, searchTerm);
// }
return searchTerm;
}
}
The simplest solution would be to use different accounts for each environment (forward mails from one to the other so both get them).
If that's not possible, the issue is with the FLAGGED flag, which is unconditionally set and excluded in the default search term.
Unfortunately, the method that sets that flag is private so you can't change that behavior.
I think the only solution is a custom search strategy that does not include NOT (FLAGGED) and keep state locally to ignore messages that you have already read.
I'm trying to set CORS properties on Azure using Java client. After executing code, I run HTML5 code to upload a file and facing following errors in chrome javascript console:
max block size = 47276
total blocks = 1
https:myacc.blob.core.windows.net/mycon/ch1.jpg?sr=c&sv=2015-04-05&sig=djbVxIBlyVy18bV0SkqNSLql1n9efAVcYnGy3VsGKis%3D&si=champ
current file pointer = 0 bytes read = 47276
block id = block-000000
https:myacc.blob.core.windows.net/mycon/ch1.jpg?sr=c&sv=2015-0…kqNSLql1n9efAVcYnGy3VsGKis%3D&si=champ&comp=block&blockid=YmxvY2stMDAwMDAw
Failed to load resource: the server responded with a status of 403 (CORS not enabled or no matching rule found for this request.)
XMLHttpRequest cannot load
https:myacc.blob.core.windows.net/mycon/ch1.jpg?sr=c&sv=2015-0…kqNSLql1n9efAVcYnGy3VsGKis%3D&si=heath&comp=block&blockid=YmxvY2stMDAwMDAw.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'file://' is therefore not allowed access. The
response had HTTP status code 403.
What I'm wondering is why it didn't set CORS if Java client was executed successfully ? Also, how do I verify if rule Policy "champ" is configured properly, if my generated SAS is correct and CORS properties are created or not
Here is Java Client code:
public class CORS_and_SAS {
public static void main(String[] args) {
// Define the connection-string with your values
final String storageConnectionString ="DefaultEndpointsProtocol=http;" + "AccountName=myacc;" + "AccountKey=B2q4AGp6YoRsTREXIkOv3e/Sxf46YzqzfnM9F8U+o7VA5Y3EiKc+CuritnvuyZxGXKNOQ5nJy2KfkniF970on1dQ==";
try {
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
// Get a reference to a container.
// The container name must be lower case
CloudBlobContainer container = blobClient.getContainerReference("mycon");
// Create the container if it does not exist.
//container.createIfNotExists();
// Set CORS support
//ServiceProperties blobServiceProperties = blobClient.GetServiceProperties();
ServiceProperties propers = getCORS();
blobClient.uploadServiceProperties(propers);
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
GregorianCalendar calendar =
new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(new Date());
policy.setSharedAccessStartTime(calendar.getTime()); //Immediately applicable
calendar.add(Calendar.HOUR, 3000); //Applicable time-span is 3000 hours
policy.setSharedAccessExpiryTime(calendar.getTime());
policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ,
SharedAccessBlobPermissions.WRITE, SharedAccessBlobPermissions.DELETE,
SharedAccessBlobPermissions.LIST));
BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
//Private container with no access for anonymous users
containerPermissions.setPublicAccess(BlobContainerPublicAccessType.OFF);
//Name the shared access policy: heath
containerPermissions.getSharedAccessPolicies().put("champ", policy);
container.uploadPermissions(containerPermissions);
//Generate the policy SAS string for heath access
String sas = container.generateSharedAccessSignature(
new SharedAccessBlobPolicy(),"champ");
System.out.println("The stored access policy signature:");
System.out.println(sas);
} catch (Exception e) {
// Output the stack trace.
e.printStackTrace();
}
}
private static ServiceProperties getCORS() {
// TODO Auto-generated method stub
ServiceProperties propers = new ServiceProperties();
CorsProperties corsprop = propers.getCors();
CorsRule cr = new CorsRule();
List<String> allowedHeaders = new ArrayList<String>();
allowedHeaders.add("x-ms-*");
List<String> exposedHeaders = new ArrayList<String>();
exposedHeaders.add("x-ms-*");
cr.setAllowedHeaders(allowedHeaders);
cr.setExposedHeaders(exposedHeaders);
EnumSet<CorsHttpMethods> allowedMethod = EnumSet.of(CorsHttpMethods.PUT,CorsHttpMethods.GET,CorsHttpMethods.POST,CorsHttpMethods.HEAD,CorsHttpMethods.DELETE);
//EnumSet<CorsHttpMethods> allowedMethod1 = EnumSet.of(CorsHttpMethods.GET);
cr.setAllowedMethods(allowedMethod);
List<String> allowedOrigin = new ArrayList<String>();
allowedOrigin.add("*");
cr.setAllowedOrigins(allowedOrigin);
cr.setMaxAgeInSeconds(600);
corsprop.getCorsRules().add(cr);
//corsprop.getCorsRules().add(cr);
propers.setCors(corsprop);
return propers;
}
}
I tried to reproduce the issue, and checked carefully the Java Client code & erros in JS console. I found that the issue was caused by using blob container Shared Access Signature for the uploading file url.
Here is the Java code modified by yours.
private static final String accountName = "<account-name>";
private static final String accountKey = "<account-key>";
private static final String connectionStringTemplate = "DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s";
private static final String containerName = "<block-blob-container-name>";
private static final String blobFileName = "<blob-file-name>";
public static void main(String[] args) throws InvalidKeyException, URISyntaxException, StorageException {
String connectionString = String.format(connectionStringTemplate, accountName, accountKey);
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudBlobClient blobClient = account.createCloudBlobClient();
/*
* Enable CORS
*/
// CORS should be enabled once at service startup
// Given a BlobClient, download the current Service Properties
ServiceProperties blobServiceProperties = blobClient.downloadServiceProperties();
// Enable and Configure CORS
CorsProperties cors = new CorsProperties();
CorsRule corsRule = new CorsRule();
List<String> allowedHeaders = new ArrayList<String>();
allowedHeaders.add("*");
EnumSet<CorsHttpMethods> allowedMethods = EnumSet.of(CorsHttpMethods.PUT, CorsHttpMethods.GET, CorsHttpMethods.HEAD, CorsHttpMethods.POST);
System.out.println(Arrays.toString(allowedMethods.toArray()));
List<String> allowedOrigins = new ArrayList<String>();
allowedOrigins.add("*");
List<String> exposedHeaders = new ArrayList<String>();
exposedHeaders.add("*");
int maxAgeInSeconds = 1800;
corsRule.setAllowedHeaders(allowedHeaders);
corsRule.setAllowedMethods(allowedMethods);
corsRule.setAllowedOrigins(allowedOrigins);
corsRule.setExposedHeaders(exposedHeaders);
corsRule.setMaxAgeInSeconds(maxAgeInSeconds);
cors.getCorsRules().add(corsRule);
blobServiceProperties.setCors(cors);
// Commit the CORS changes into the Service Properties
blobClient.uploadServiceProperties(blobServiceProperties);
/*
* Generate the SAS for the uploading url
*/
CloudBlobContainer container = blobClient.getContainerReference(containerName);
CloudBlockBlob blockBlob = container.getBlockBlobReference(blobFileName);
SharedAccessBlobPolicy sharedAccessBlobPolicy = new SharedAccessBlobPolicy();
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(new Date());
sharedAccessBlobPolicy.setSharedAccessStartTime(calendar.getTime());
calendar.add(Calendar.HOUR, 1);
sharedAccessBlobPolicy.setSharedAccessExpiryTime(calendar.getTime());
sharedAccessBlobPolicy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.WRITE));
String sas = blockBlob.generateSharedAccessSignature(sharedAccessBlobPolicy, null);
System.out.println(sas);
String blobUploadSASURL = String.format("https://%s.blob.core.windows.net/%s/%s?%s", accountName, containerName, blobFileName, sas);
System.out.println(blobUploadSASURL);
}
Run the code and get the uploading blob SAS Url as the form https://<account-name>.blob.core.windows.net/<container>/<blob-file-name>?sig=<SIG>&st=2015-12-01T11%3A51%3A20Z&se=2015-12-01T12%3A51%3A20Z&sv=2015-04-05&sp=r&sr=b
Using PUT method with header x-ms-blob-type: BlockBlob for the URL to upload a file successfully.
Further details and sample ajax code to do this is available, please refer to the blog from the Azure Storage team http://blogs.msdn.com/b/windowsazurestorage/archive/2014/02/03/windows-azure-storage-introducing-cors.aspx.
I want to send MMS from my application to a specific number. I've searched and found this code but I have no idea if this code what I need or not.
My Questions is :
-can anyone explain this code to me.i am beginner in MMS.
-also, i thought this code is let the user send MMS from my application without move it to the native Messaging inbox (and this is what i want) Am i right?
-also i have a problem ,i do not know how can i put this code in my project.
this is what i found
MMS is just a http-post request. You should perform the request using extra network feature :
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = connMgr.startUsingNetworkFeature( ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_MMS);
If you get back the result with Phone.APN_REQUEST_STARTED value, you have to wait for proper state. Register BroadCastReciver and wait until Phone.APN_ALREADY_ACTIVE appears:
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(reciver, filter);
If background connection is ready, then build content and perform request. If you want to do that using android's internal code, please use this:
final SendReq sendRequest = new SendReq();
final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
if (sub != null && sub.length > 0) {
sendRequest.setSubject(sub[0]);
}
final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipient);
if (phoneNumbers != null && phoneNumbers.length > 0) {
sendRequest.addTo(phoneNumbers[0]);
}
final PduBody pduBody = new PduBody();
if (parts != null) {
for (MMSPart part : parts) {
final PduPart partPdu = new PduPart();
partPdu.setName(part.Name.getBytes());
partPdu.setContentType(part.MimeType.getBytes());
partPdu.setData(part.Data);
pduBody.addPart(partPdu);
}
}
sendRequest.setBody(pduBody);
final PduComposer composer = new PduComposer(this.context, sendRequest);
final byte[] bytesToSend = composer.make();
HttpUtils.httpConnection(context, 4444L, MMSCenterUrl, bytesToSendFromPDU, HttpUtils.HTTP_POST_METHOD, !TextUtils.isEmpty(MMSProxy), MMSProxy, port);
MMSCenterUrl: url from MMS-APNs,
MMSProxy: proxy from MMS-APNs,
port: port from MMS-APNs
Note that some classes are from internal packages. Download from android git is required.
The request should be done with url from user's apn-space code:
public class APNHelper {
public class APN {
public String MMSCenterUrl = "";
public String MMSPort = "";
public String MMSProxy = "";
}
public APNHelper(final Context context) {
this.context = context;
}
public List<APN> getMMSApns() {
final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"), null, null, null, null);
if ( apnCursor == null ) {
return Collections.EMPTY_LIST;
} else {
final List<APN> results = new ArrayList<APN>();
while ( apnCursor.moveToNext() ) {
final String type = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.TYPE));
if ( !TextUtils.isEmpty(type) && ( type.equalsIgnoreCase(Phone.APN_TYPE_ALL) || type.equalsIgnoreCase(Phone.APN_TYPE_MMS) ) ) {
final String mmsc = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSC));
final String mmsProxy = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
final String port = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPORT));
final APN apn = new APN();
apn.MMSCenterUrl = mmsc;
apn.MMSProxy = mmsProxy;
apn.MMSPort = port;
results.add(apn);
}
}
apnCursor.close();
return results;
}
Please help me
why don't you use the android system functions:
Please have a look on
https://developer.android.com/guide/components/intents-common.html
public void composeMmsMessage(String message, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("smsto:")); // This ensures only SMS apps respond
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent); }
}
Cheers
Tom
I found a link in an other thread to a github project that works 100% https://github.com/klinker41/android-smsmms
Notice, that obligatory settings are only
Settings sendSettings = new Settings();
sendSettings.setMmsc(mmsc);
sendSettings.setProxy(proxy);
sendSettings.setPort(port);
you can get them something like (found at Set APN programmatically on Android - answear by vincent091):
Cursor cursor = null;
if (Utils.hasICS()){
cursor =SqliteWrapper.query(activity, activity.getContentResolver(),
Uri.withAppendedPath(Carriers.CONTENT_URI, "current"), APN_PROJECTION, null, null, null);
} else {
cursor = activity.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"),
null, null, null, null);
}
cursor.moveToLast();
String type = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.TYPE));
String mmsc = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSC));
String proxy = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
String port = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSPORT));